<!doctype html>
<html lang="zh-cn">
<head>

    <meta charset="utf-8">
    <meta name="generator" content="Hugo 0.57.2" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Thymeleaf 文档 | The Sky of OtsWang</title>
    <meta property="og:title" content="Thymeleaf 文档 - The Sky of OtsWang">
    <meta property="og:type" content="article">
        
    <meta property="article:published_time" content="2019-03-13T10:03:32&#43;08:00">
        
        
    <meta property="article:modified_time" content="2019-03-13T10:03:41&#43;08:00">
        
    <meta name="Keywords" content="golang,go语言,otswang,java,博客,python">
    <meta name="description" content="Thymeleaf 文档">
        
    <meta name="author" content="OtsWang">
    <meta property="og:url" content="https://otswang.gitee.io/hugo/post/doc_api/thymeleaf_doc/">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="/hugo/css/normalize.css">
    
        <link rel="stylesheet" href="/hugo/css/prism.css">
    
    <link rel="stylesheet" href="/hugo/css/style.css">
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>

    


    
    
</head>

<body>
<header id="header" class="clearfix">
    <div class="container">
        <div class="col-group">
            <div class="site-name ">
                
                    <a id="logo" href="https://otswang.gitee.io/hugo/">
                        The Sky of OtsWang
                    </a>
                
                <p class="description">擅长写HelloWorld的小小码农</p>
            </div>
            <div>
                <nav id="nav-menu" class="clearfix">
                    
                    
                    <a  href="https://otswang.gitee.io/hugo/" title="Home">Home</a>
                    
                    <a  href="https://otswang.gitee.io/hugo/tags/" title="Tags">Tags</a>
                    
                    <a  href="https://otswang.gitee.io/hugo/categories/" title="Categories">Categories</a>
                    
                    <a  href="https://otswang.gitee.io/hugo/archives/" title="Archives">Archives</a>
                    
                    <a  href="https://otswang.gitee.io/hugo/about/" title="About">About</a>
                    
                </nav>
            </div>
        </div>
    </div>
</header>


<div id="body">
    <div class="container">
        <div class="col-group">

            <div class="col-8" id="main">
                <div class="res-cons">
                    <article class="post">
                        <header>
                            <h1 class="post-title">Thymeleaf 文档</h1>
                        </header>
                        <date class="post-meta meta-date">
                            2019年3月13日
                        </date>
                        
                        <div class="post-meta">
                            <span>|</span>
                            
                                <span class="meta-category"><a href="https://otswang.gitee.io/hugo/categories/doc">Doc</a></span>
                            
                        </div>
                        
                        
                        
                        <div class="post-content">
                            <p><strong>Tutorial: Using Thymeleaf</strong></p>

<div align=center>
      <img src="https://www.thymeleaf.org/doc/images/thymeleaf.png" width="150"  />
</div>

<h1 id="1-introducing-thymeleaf">1. Introducing Thymeleaf</h1>

<h2 id="1-1-what-is-thymeleaf">1.1. What is Thymeleaf?</h2>

<p>Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.</p>

<p>The main goal of Thymeleaf is to provide an elegant and highly-maintainable(高度可维护) way of creating templates. To achieve this, it builds on the concept of Natural Templates to inject its logic into template files in a way that doesn’t affect the template from being used as a design prototype. This improves communication of design and bridges the gap between design and development teams.</p>

<p>Thymeleaf has also been designed from the beginning with Web Standards in mind – especially HTML5 – allowing you to create fully validating templates if that is a need for you.</p>

<h2 id="1-2-what-kind-of-templates-can-thymeleaf-process">1.2. What kind of templates can Thymeleaf process?</h2>

<p>Out-of-the-box, Thymeleaf allows you to process six kinds of templates, each of which is called a Template Mode:</p>

<pre><code>HTML
XML
TEXT
JAVASCRIPT
CSS
RAW
</code></pre>

<p>There are two markup template modes (HTML and XML), three textual template modes (TEXT, JAVASCRIPT and CSS) and a no-op template mode (RAW).</p>

<p>The HTML template mode will allow any kind of HTML input, including HTML5, HTML 4 and XHTML. No validation or well-formedness check will be performed, and template code/structure will be respected to the biggest possible extent in output.</p>

<p>The XML template mode will allow XML input. In this case, code is expected to be well-formed – no unclosed tags, no unquoted attributes, etc – and the parser will throw exceptions if well-formedness violations are found. Note that no validation (against a DTD or XML Schema) will be performed.</p>

<p>The TEXT template mode will allow the use of a special syntax for templates of a non-markup nature. Examples of such templates might be text emails or templated documentation. Note that HTML or XML templates can be also processed as TEXT, in which case they will not be parsed as markup, and every tag, DOCTYPE, comment, etc, will be treated as mere text.</p>

<p>The JAVASCRIPT template mode will allow the processing of JavaScript files in a Thymeleaf application. This means being able to use model data inside JavaScript files in the same way it can be done in HTML files, but with JavaScript-specific integrations such as specialized escaping or natural scripting. The JAVASCRIPT template mode is considered a textual mode and therefore uses the same special syntax as the TEXT template mode.</p>

<p>The CSS template mode will allow the processing of CSS files involved in a Thymeleaf application. Similar to the JAVASCRIPT mode, the CSS template mode is also a textual mode and uses the special processing syntax from the TEXT template mode.</p>

<p>The RAW template mode will simply not process templates at all. It is meant to be used for inserting untouched resources (files, URL responses, etc.) into the templates being processed. For example, external, uncontrolled resources in HTML format could be included into application templates, safely knowing that any Thymeleaf code that these resources might include will not be executed.
1.3 Dialects: The Standard Dialect</p>

<p>Thymeleaf is an extremely extensible template engine (in fact it could be called a template engine framework) that allows you to define and customize the way your templates will be processed to a fine level of detail.</p>

<p>An object that applies some logic to a markup artifact (a tag, some text, a comment, or a mere placeholder if templates are not markup) is called a processor, and a set of these processors – plus perhaps some extra artifacts – is what a dialect is normally comprised of. Out of the box, Thymeleaf’s core library provides a dialect called the Standard Dialect, which should be enough for most users.</p>

<p>Note that dialects can actually have no processors and be entirely comprised of other kinds of artifacts, but processors are definitely the most common use case.</p>

<p>This tutorial covers the Standard Dialect. Every attribute and syntax feature you will learn about in the following pages is defined by this dialect, even if that isn’t explicitly mentioned.</p>

<p>Of course, users can create their own dialects (even extending the Standard one) if they want to define their own processing logic while taking advantage of the library’s advanced features. Thymeleaf can also be configured to use several dialects at a time.</p>

<p><strong>Note that</strong> The official thymeleaf-spring3 and thymeleaf-spring4 integration(结合，一体化) packages both define a dialect called the “SpringStandard Dialect”, which is mostly the same as the Standard Dialect, but with small adaptations to make better use of some features in the Spring Framework (for example, by using Spring Expression Language or SpringEL instead of OGNL). <strong>So if you are a Spring MVC user you are not wasting your time, as almost everything you learn here will be of use in your Spring applications</strong> .</p>

<p>Most of the processors of the Standard Dialect are <strong>attribute processors</strong>. This allows browsers to correctly display HTML template files even before being processed because they will simply ignore the additional attributes. For example, while a JSP using tag libraries could include a fragment of code not directly displayable by a browser like:</p>

<pre><code class="language-html">&lt;form:inputText name=&quot;userName&quot; value=&quot;${user.name}&quot; /&gt;
</code></pre>

<p>the Thymeleaf Standard Dialect would allow us to achieve the same functionality with:</p>

<pre><code class="language-html">&lt;input type=&quot;text&quot; name=&quot;userName&quot; value=&quot;James Carrot&quot; th:value=&quot;${user.name}&quot; /&gt;
</code></pre>

<p>Not only will this be correctly displayed by browsers, but this also allow us to (optionally) specify a value attribute in it (“James Carrot”, in this case) that will be displayed when the prototype is statically opened in a browser, and that will be substituted by the value resulting from the evaluation of ${user.name} during processing of the template.</p>

<p>This helps your designer and developer to work on the very same template file and reduce the effort required to transform a static prototype into a working template file. The ability to do this is a feature called Natural Templating.</p>

<h1 id="2-the-good-thymes-virtual-grocery">2. The Good Thymes Virtual Grocery</h1>

<p>The source code for the examples shown in this, and future chapters of this guide, can be found in the <em>Good Thymes Virtual Grocery(杂货店)</em> GitHub repository.</p>

<h2 id="2-1-a-website-for-a-grocery">2.1. A website for a grocery</h2>

<p>To better explain the concepts involved in processing templates with Thymeleaf, this tutorial will use a demo application which you can download from the project’s web site.</p>

<p>This application is the web site of an imaginary virtual grocery, and will provide us with many scenarios(脚本) to showcase Thymeleaf’s many features.</p>

<p>To start, we need a simple set of model entities for our application: Products which are sold to Customers by creating Orders. We will also be managing Comments about those Products:</p>

<p><img src="https://www.thymeleaf.org/doc/tutorials/3.0/images/usingthymeleaf/gtvg-model.png" alt="Example application model" /></p>

<p>Our application will also have a very simple service layer, composed by Service objects containing methods like:</p>

<pre><code class="language-java">public class ProductService {

    ...

    public List&lt;Product&gt; findAll() {
        return ProductRepository.getInstance().findAll();
    }

    public Product findById(Integer id) {
        return ProductRepository.getInstance().findById(id);
    }
    
}
</code></pre>

<p>At the web layer our application will have a filter that will delegate(代表) execution to Thymeleaf-enabled commands depending on the request URL:</p>

<pre><code class="language-java">private boolean process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    
    try {

        // This prevents triggering engine executions for resource URLs
        if (request.getRequestURI().startsWith(&quot;/css&quot;) ||
                request.getRequestURI().startsWith(&quot;/images&quot;) ||
                request.getRequestURI().startsWith(&quot;/favicon&quot;)) {
            return false;
        }

        
        /*
         * Query controller/URL mapping and obtain the controller
         * that will process the request. If no controller is available,
         * return false and let other filters/servlets process the request.
         */
        IGTVGController controller = this.application.resolveControllerForRequest(request);
        if (controller == null) {
            return false;
        }

        /*
         * Obtain the TemplateEngine instance.
         */
        ITemplateEngine templateEngine = this.application.getTemplateEngine();

        /*
         * Write the response headers
         */
        response.setContentType(&quot;text/html;charset=UTF-8&quot;);
        response.setHeader(&quot;Pragma&quot;, &quot;no-cache&quot;);
        response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;);
        response.setDateHeader(&quot;Expires&quot;, 0);

        /*
         * Execute the controller and process view template,
         * writing the results to the response writer. 
         */
        controller.process(
                request, response, this.servletContext, templateEngine);
        
        return true;
        
    } catch (Exception e) {
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (final IOException ignored) {
            // Just ignore this
        }
        throw new ServletException(e);
    }
    
}

</code></pre>

<p>This is our IGTVGController interface:</p>

<pre><code class="language-java">public interface IGTVGController {

    public void process(
            HttpServletRequest request, HttpServletResponse response,
            ServletContext servletContext, ITemplateEngine templateEngine);    
    
}
</code></pre>

<p>All we have to do now is create implementations of the IGTVGController interface, <strong>retrieving data from the services and processing templates using the ITemplateEngine object.</strong></p>

<p>In the end, it will look like this:</p>

<p><img src="https://www.thymeleaf.org/doc/tutorials/3.0/images/usingthymeleaf/gtvg-view.png" alt="Example application home page" /></p>

<p>But first let’s see how that template engine is initialized.</p>

<h2 id="2-2-creating-and-configuring-the-template-engine">2.2. Creating and configuring the Template Engine</h2>

<p>The <code>process(…)</code> method in our filter contained this line:</p>

<pre><code class="language-java">ITemplateEngine templateEngine = this.application.getTemplateEngine();
</code></pre>

<p>Which means that the GTVGApplication class is in charge of creating and configuring one of the most important objects in a Thymeleaf application: the TemplateEngine instance (implementation of the ITemplateEngine interface).</p>

<p>Our org.thymeleaf.TemplateEngine object is initialized like this:</p>

<pre><code class="language-java">public class GTVGApplication {
  
    
    ...
    private final TemplateEngine templateEngine;
    ...
    
    
    public GTVGApplication(final ServletContext servletContext) {

        super();

        ServletContextTemplateResolver templateResolver = 
                new ServletContextTemplateResolver(servletContext);
        
        // HTML is the default mode, but we set it anyway for better understanding of code
        templateResolver.setTemplateMode(TemplateMode.HTML);
        // This will convert &quot;home&quot; to &quot;/WEB-INF/templates/home.html&quot;
        templateResolver.setPrefix(&quot;/WEB-INF/templates/&quot;);
        templateResolver.setSuffix(&quot;.html&quot;);
        // Template cache TTL=1h. If not set, entries would be cached until expelled
        templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
        
        // Cache is set to true by default. Set to false if you want templates to
        // be automatically updated when modified.
        templateResolver.setCacheable(true);
        
        this.templateEngine = new TemplateEngine();
        this.templateEngine.setTemplateResolver(templateResolver);
        
        ...

    }

}

</code></pre>

<p>There are many ways of configuring a TemplateEngine object, but for now these few lines of code will teach us enough about the steps needed.
The Template Resolver</p>

<p>Let’s start with the Template Resolver:</p>

<pre><code class="language-java">ServletContextTemplateResolver templateResolver = 
        new ServletContextTemplateResolver(servletContext);
</code></pre>

<p>Template Resolvers are objects that implement an interface from the Thymeleaf API called org.thymeleaf.templateresolver.ITemplateResolver:</p>

<pre><code class="language-java">public interface ITemplateResolver {

    ...
  
    /*
     * Templates are resolved by their name (or content) and also (optionally) their 
     * owner template in case we are trying to resolve a fragment for another template.
     * Will return null if template cannot be handled by this template resolver.
     */
    public TemplateResolution resolveTemplate(
            final IEngineConfiguration configuration,
            final String ownerTemplate, final String template,
            final Map&lt;String, Object&gt; templateResolutionAttributes);
}

</code></pre>

<p>These objects are in charge of determining how our templates will be accessed, and in this GTVG application, the <code>org.thymeleaf.templateresolver.ServletContextTemplateResolver</code> means that we are going to retrieve our template files as resources from the Servlet Context: an application-wide <code>javax.servlet.ServletContext</code> object that exists in every Java web application, and that resolves resources from the web application root.</p>

<p>But that’s not all we can say about the template resolver, because we can set some configuration parameters on it. First, the template mode:</p>

<pre><code class="language-java">templateResolver.setTemplateMode(TemplateMode.HTML);
</code></pre>

<p>HTML is the default template mode for ServletContextTemplateResolver, but it is good practice to establish it anyway so that our code documents clearly what is going on.</p>

<pre><code>templateResolver.setPrefix(&quot;/WEB-INF/templates/&quot;);
templateResolver.setSuffix(&quot;.html&quot;);
</code></pre>

<p>The prefix and suffix modify the template names that we will be passing to the engine for obtaining the real resource names to be used.</p>

<p>Using this configuration, the template name “product/list” would correspond to:</p>

<pre><code>servletContext.getResourceAsStream(&quot;/WEB-INF/templates/product/list.html&quot;)
</code></pre>

<p>Optionally, <strong>the amount of time that a parsed template can live in the cache is configured at the Template Resolver by means of the cacheTTLMs property</strong>:</p>

<pre><code class="language-java">templateResolver.setCacheTTLMs(3600000L);
</code></pre>

<p>A template can still be expelled from cache before that TTL is reached if the max cache size is reached and it is the oldest entry currently cached(先进先出).</p>

<p>Cache behaviour and sizes can be defined by the user by implementing the ICacheManager interface or by modifying the StandardCacheManager object to manage the default cache.</p>

<p>There is much more to learn about template resolvers, but for now let’s have a look at the creation of our Template Engine object.
The Template Engine</p>

<p>Template Engine objects are implementations of the <code>org.thymeleaf.ITemplateEngine</code> interface. One of these implementations is offered by the Thymeleaf core: <code>org.thymeleaf.TemplateEngine</code>, and we create an instance of it here:</p>

<pre><code class="language-java">templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
</code></pre>

<p>Rather simple, isn’t it? All we need is to <strong>create an instance and set the Template Resolver to it</strong>.</p>

<p>A template resolver is the only required parameter a TemplateEngine needs, although there are many others that will be covered later (message resolvers, cache sizes, etc). For now, this is all we need.</p>

<p>Our Template Engine is now ready and we can start creating our pages using Thymeleaf.</p>

<h1 id="3-using-texts">3. Using Texts</h1>

<h2 id="3-1-a-multi-language-welcome">3.1. A multi-language welcome</h2>

<p>Our first task will be to create a home page for our grocery site.</p>

<p>The first version of this page will be extremely simple: just a title and a welcome message. This is our <code>/WEB-INF/templates/home.html</code> file:</p>

<pre><code class="language-html">&lt;!DOCTYPE html&gt;

&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;

  &lt;head&gt;
    &lt;title&gt;Good Thymes Virtual Grocery&lt;/title&gt;
    &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot; 
          href=&quot;../../css/gtvg.css&quot; th:href=&quot;@{/css/gtvg.css}&quot; /&gt;
  &lt;/head&gt;

  &lt;body&gt;
  
    &lt;p th:text=&quot;#{home.welcome}&quot;&gt;Welcome to our grocery store!&lt;/p&gt;
  
  &lt;/body&gt;

&lt;/html&gt;
</code></pre>

<p>The first thing you will notice is that this file is HTML5 that can be correctly displayed by any browser because it does not include any non-HTML tags (<em>browsers ignore all attributes they don’t understand, like th:text</em>).</p>

<p>But you may also notice that this template is not really a valid HTML5 document, because these non-standard attributes we are using in the th:* form are not allowed by the HTML5 specification. In fact, we are even adding an xmlns:th attribute to our <html> tag, something absolutely non-HTML5-ish:</p>

<pre><code class="language-html">&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;
</code></pre>

<p>which has no influence at all in template processing, but works as an incantation that prevents our IDE from complaining about the lack of a namespace definition for all those <code>th:*</code> attributes.</p>

<p>So what if we wanted to make this template HTML5-valid? Easy: switch to Thymeleaf’s data attribute syntax, using the data- prefix for attribute names and hyphen (-) separators instead of semi-colons (:):</p>

<pre><code class="language-html">&lt;!DOCTYPE html&gt;

&lt;html&gt;

  &lt;head&gt;
    &lt;title&gt;Good Thymes Virtual Grocery&lt;/title&gt;
    &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot; 
          href=&quot;../../css/gtvg.css&quot; data-th-href=&quot;@{/css/gtvg.css}&quot; /&gt;
  &lt;/head&gt;

  &lt;body&gt;
  
    &lt;p data-th-text=&quot;#{home.welcome}&quot;&gt;Welcome to our grocery store!&lt;/p&gt;
  
  &lt;/body&gt;

&lt;/html&gt;
</code></pre>

<p>Custom <code>data-</code> prefixed attributes are allowed by the HTML5 specification, so, with this code above, our template would be a valid HTML5 document.</p>

<p>Both notations are completely equivalent(相等的，相当的) and interchangeable, but for the sake of simplicity and compactness of the code samples, this tutorial will use the namespace notation <code>(th:*)</code>. Also, the<code>th:*</code> notation is more general and allowed in every Thymeleaf template mode (XML, TEXT…) whereas the <code>data-</code> notation is only allowed in HTML mode.</p>

<p><strong>Using th:text and externalizing text</strong></p>

<p>Externalizing text is extracting fragments of template code out of template files so that they can be kept in separate files (typically .properties files) and that they can be easily replaced with equivalent texts written in other languages (a process called internationalization or simply i18n). Externalized fragments of text are usually called “messages”.</p>

<p>Messages always have a key that identifies them, and Thymeleaf allows you to specify that a text should correspond to a specific message with the #{&hellip;} syntax:</p>

<pre><code class="language-html">&lt;p th:text=&quot;#{home.welcome}&quot;&gt;Welcome to our grocery store!&lt;/p&gt;
</code></pre>

<p>What we can see here are in fact two different features of the Thymeleaf Standard Dialect:</p>

<ul>
<li>The <code>th:text</code> attribute, which evaluates its value expression and sets the result as the body of the host tag, effectively replacing the “Welcome to our grocery store!” text we see in the code.</li>
<li>The <code>#{home.welcome}</code> expression, specified in the Standard Expression Syntax, instructing that the text to be used by the <code>th:text</code> attribute should be the message with the <code>home.welcome</code> key corresponding to whichever locale we are processing the template with.</li>
</ul>

<p>Now, where is this externalized text?</p>

<p>The location of externalized text in Thymeleaf is fully configurable, and it will depend on the specific <code>org.thymeleaf.messageresolver.IMessageResolver</code> implementation being used. Normally, an implementation based on .properties files will be used, but we could create our own implementations if we wanted, for example, to obtain messages from a database.</p>

<p>However, we have not specified a message resolver for our template engine during initialization, and that means that our application is using the Standard Message Resolver, implemented by <code>org.thymeleaf.messageresolver.StandardMessageResolver</code>.</p>

<p>The standard message resolver expects to find messages for /WEB-INF/templates/home.html in properties files in the same folder and with the same name as the template, like:</p>

<ul>
<li>/WEB-INF/templates/home_en.properties for English texts.</li>
<li>/WEB-INF/templates/home_es.properties for Spanish language texts.</li>
<li>/WEB-INF/templates/home_pt_BR.properties for Portuguese (Brazil) language texts.</li>
<li>/WEB-INF/templates/home.properties for default texts (if the locale is not matched).</li>
</ul>

<p>Let’s have a look at our home_es.properties file:</p>

<p>home.welcome=¡Bienvenido a nuestra tienda de comestibles!</p>

<p>This is all we need for making Thymeleaf process our template. Let’s create our Home controller then.</p>

<p><strong>Contexts</strong></p>

<p>In order to process our template, we will create a <code>HomeController</code> class implementing the <code>IGTVGController</code> interface we saw before:</p>

<pre><code class="language-java">public class HomeController implements IGTVGController {

    public void process(
            final HttpServletRequest request, final HttpServletResponse response,
            final ServletContext servletContext, final ITemplateEngine templateEngine)
            throws Exception {
        
        WebContext ctx = 
                new WebContext(request, response, servletContext, request.getLocale());
        
        templateEngine.process(&quot;home&quot;, ctx, response.getWriter());
        
    }

}
</code></pre>

<p>The first thing we see is the creation of a context. A Thymeleaf context is an object implementing the <code>org.thymeleaf.context.IContext</code> interface. Contexts should contain all the data required for an execution of the template engine in a variables map, and also reference the locale that must be used for externalized messages.</p>

<pre><code class="language-java">public interface IContext {

    public Locale getLocale();
    public boolean containsVariable(final String name);
    public Set&lt;String&gt; getVariableNames();
    public Object getVariable(final String name);
    
}
</code></pre>

<p>There is a specialized extension of this interface, <code>org.thymeleaf.context.IWebContext</code>, meant to be used in ServletAPI-based web applications (like SpringMVC).</p>

<pre><code class="language-java">public interface IWebContext extends IContext {
    
    public HttpServletRequest getRequest();
    public HttpServletResponse getResponse();
    public HttpSession getSession();
    public ServletContext getServletContext();
    
}
</code></pre>

<p>The Thymeleaf core library offers an implementation of each of these interfaces:</p>

<blockquote>
<p>org.thymeleaf.context.Context implements IContext</p>

<p>org.thymeleaf.context.WebContext implements IWebContext</p>
</blockquote>

<p>And as you can see in the controller code, WebContext is the one we use. In fact we have to, because the use of a <code>ServletContextTemplateResolver</code> requires that we use a context implementing <code>IWebContext</code>.</p>

<pre><code class="language-java">WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
</code></pre>

<p>Only three out of those four constructor arguments are required because the default locale for the system will be used if none is specified (although you should never let this happen in real applications).</p>

<p>There are some specialized expressions that we will be able to use to obtain the request parameters and the <em>request, session and application</em> attributes from the WebContext in our templates. For example:</p>

<pre><code>${x} will return a variable x stored into the Thymeleaf context or as a request attribute.
${param.x} will return a request parameter called x (which might be multivalued).
${session.x} will return a session attribute called x.
${application.x} will return a servlet context attribute called x.
</code></pre>

<p><strong>Executing the template engine</strong></p>

<p>With our context object ready, now we can tell the template engine to process the template (by its name) using the context, and passing it a response writer so that the response can be written to it:</p>

<pre><code class="language-java">templateEngine.process(&quot;home&quot;, ctx, response.getWriter());
</code></pre>

<p>Let’s see the results of this using the Spanish locale:</p>

<pre><code class="language-html">&lt;!DOCTYPE html&gt;

&lt;html&gt;

  &lt;head&gt;
    &lt;title&gt;Good Thymes Virtual Grocery&lt;/title&gt;
    &lt;meta content=&quot;text/html; charset=UTF-8&quot; http-equiv=&quot;Content-Type&quot;/&gt;
    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot; href=&quot;/gtvg/css/gtvg.css&quot; /&gt;
  &lt;/head&gt;

  &lt;body&gt;
  
    &lt;p&gt;¡Bienvenido a nuestra tienda de comestibles!&lt;/p&gt;

  &lt;/body&gt;

&lt;/html&gt;

</code></pre>

<h2 id="3-2-more-on-texts-and-variables">3.2. More on texts and variables</h2>

<p><strong>Unescaped Text</strong></p>

<p>The simplest version of our Home page seems to be ready now, but there is something we have not thought about. what if we had a message like this?</p>

<pre><code>  home.welcome=Welcome to our &lt;b&gt;fantastic&lt;/b&gt; grocery store!
</code></pre>

<p>If we execute this template like before, we will obtain:</p>

<p>Welcome to our &lt;b&gt;fantastic&lt;/b&gt; grocery store!</p>

<p>Which is not exactly what we expected, because our <code>&lt;b&gt;</code> tag has been escaped and therefore it will be displayed in the browser.</p>

<p>This is the default behaviour of the <code>th:text</code> attribute. If we want Thymeleaf to respect our HTML tags and not escape them, we will have to use a different attribute: <code>th:utext</code> (for “unescaped text”):</p>

<pre><code class="language-html">&lt;p th:utext=&quot;#{home.welcome}&quot;&gt;Welcome to our grocery store!&lt;/p&gt;
</code></pre>

<p>This will output our message just like we wanted it:</p>

<p>Welcome to our <b>fantastic</b> grocery store!</p>

<p><strong>Using and displaying variables</strong></p>

<p>Now let’s add some more content to our home page. For example, we may want to display the date below our welcome message, like this:</p>

<pre><code>  Welcome to our fantastic grocery store!

  Today is: 12 july 2010
</code></pre>

<p>First of all, we will have to modify our controller so that we add that date as a context variable:</p>

<pre><code class="language-java">public void process(
            final HttpServletRequest request, final HttpServletResponse response,
            final ServletContext servletContext, final ITemplateEngine templateEngine)
            throws Exception {
        
    SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;dd MMMM yyyy&quot;);
    Calendar cal = Calendar.getInstance();
        
    WebContext ctx = 
            new WebContext(request, response, servletContext, request.getLocale());
    ctx.setVariable(&quot;today&quot;, dateFormat.format(cal.getTime()));
        
    templateEngine.process(&quot;home&quot;, ctx, response.getWriter());
        
}
</code></pre>

<p>We have added a String variable called today to our context, and now we can display it in our template:</p>

<pre><code class="language-html">&lt;body&gt;

  &lt;p th:utext=&quot;#{home.welcome}&quot;&gt;Welcome to our grocery store!&lt;/p&gt;

  &lt;p&gt;Today is: &lt;span th:text=&quot;${today}&quot;&gt;13 February 2011&lt;/span&gt;&lt;/p&gt;
  
&lt;/body&gt;
</code></pre>

<p>As you can see, we are still using the <code>th:text</code> attribute for the job (and that’s correct, because we want to replace the tag’s body), but the syntax is a little bit different this time and instead of a <code>#{...}</code> expression value, we are using a <code>${...}</code> one. This is a <strong>variable expression</strong>, and it contains an expression in a language called <strong>OGNL (Object-Graph Navigation Language)</strong> that will be executed on the context variables map we talked about before.</p>

<p>The <code>${today}</code> expression simply means “get the variable called today”, but these expressions could be more complex (like ${user.name} for “get the variable called user, and call its getName() method”).</p>

<p>There are quite a lot of possibilities in attribute values: messages, variable expressions&hellip; and quite a lot more. The next chapter will show us what all these possibilities are.</p>

<h1 id="4-standard-expression-syntax">4. Standard Expression Syntax</h1>

<p>We will take a small break in the development of our grocery virtual store to learn about one of the most important parts of the Thymeleaf Standard Dialect: the Thymeleaf Standard Expression syntax.</p>

<p>We have already seen two types of valid attribute values expressed in this syntax: message and variable expressions:</p>

<pre><code class="language-html">&lt;p th:utext=&quot;#{home.welcome}&quot;&gt;Welcome to our grocery store!&lt;/p&gt;

&lt;p&gt;Today is: &lt;span th:text=&quot;${today}&quot;&gt;13 february 2011&lt;/span&gt;&lt;/p&gt;
</code></pre>

<p>But there are more types of expressions, and more interesting details to learn about the ones we already know. First, let’s see a quick summary of the Standard Expression features:</p>

<pre><code>Simple expressions:
    Variable Expressions: ${...}
    Selection Variable Expressions: *{...}
    Message Expressions: #{...}
    Link URL Expressions: @{...}
    Fragment Expressions: ~{...}
Literals
    Text literals: 'one text', 'Another one!',…
    Number literals: 0, 34, 3.0, 12.3,…
    Boolean literals: true, false
    Null literal: null
    Literal tokens: one, sometext, main,…
Text operations:
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:
    Binary operators: +, -, *, /, %
    Minus sign (unary operator): -
Boolean operations:
    Binary operators: and, or
    Boolean negation (unary operator): !, not
Comparisons and equality:
    Comparators: &gt;, &lt;, &gt;=, &lt;= (gt, lt, ge, le)
    Equality operators: ==, != (eq, ne)
Conditional operators:
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:
    No-Operation: _
</code></pre>

<p>All these features can be combined and nested:</p>

<pre><code class="language-html">'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
</code></pre>

<h2 id="4-1-messages">4.1. Messages</h2>

<p>As we already know, #{&hellip;} message expressions allow us to link this:</p>

<pre><code class="language-html">&lt;p th:utext=&quot;#{home.welcome}&quot;&gt;Welcome to our grocery store!&lt;/p&gt;
</code></pre>

<p>to this:</p>

<pre><code>  home.welcome=¡Bienvenido a nuestra tienda de comestibles!
</code></pre>

<p>But there’s one aspect we still haven’t thought of: what happens if the message text is not completely static? What if, for example, our application knew who is the user visiting the site at any moment and we wanted to greet them by name?</p>

<pre><code class="language-html">&lt;p&gt;¡Bienvenido a nuestra tienda de comestibles, John Apricot!&lt;/p&gt;
</code></pre>

<p>This means we would need to add a parameter to our message. Just like this:</p>

<pre><code>  home.welcome=¡Bienvenido a nuestra tienda de comestibles, {0}!
</code></pre>

<p>Parameters are specified according to the <code>java.text.MessageFormat</code> standard syntax, which means you can format to numbers and dates as specified in the API docs for classes in the <code>java.text.*</code> package.</p>

<p>In order to specify a value for our parameter, and given an HTTP session attribute called user, we could have:</p>

<pre><code class="language-html">&lt;p th:utext=&quot;#{home.welcome(${session.user.name})}&quot;&gt;
  Welcome to our grocery store, Sebastian Pepper!
&lt;/p&gt;
</code></pre>

<blockquote>
<p>Note that the use of <code>th:utext</code> here means that the formatted message will not be escaped. This example assumes that user.name is already escaped.</p>
</blockquote>

<p>Several parameters can be specified, separated by commas(,).</p>

<p>The message key itself can come from a variable:</p>

<pre><code class="language-html">&lt;p th:utext=&quot;#{${welcomeMsgKey}(${session.user.name})}&quot;&gt;
  Welcome to our grocery store, Sebastian Pepper!
&lt;/p&gt;
</code></pre>

<h2 id="4-2-variables">4.2. Variables</h2>

<p>We already mentioned that <code>${...}</code> expressions are in fact OGNL (Object-Graph Navigation Language) expressions executed on the map of variables contained in the context.</p>

<p>For detailed info about OGNL syntax and features, you should read the OGNL Language Guide</p>

<p>In Spring MVC-enabled applications OGNL will be replaced with SpringEL, but its syntax is very similar to that of OGNL (actually, exactly the same for most common cases).</p>

<p>From OGNL’s syntax, we know that the expression in:</p>

<pre><code class="language-html">&lt;p&gt;Today is: &lt;span th:text=&quot;${today}&quot;&gt;13 february 2011&lt;/span&gt;.&lt;/p&gt;
</code></pre>

<p>is in fact equivalent to this:</p>

<pre><code class="language-html">ctx.getVariable(&quot;today&quot;);
</code></pre>

<p>But OGNL allows us to create quite more powerful expressions, and that’s how this:</p>

<pre><code class="language-html">&lt;p th:utext=&quot;#{home.welcome(${session.user.name})}&quot;&gt;
  Welcome to our grocery store, Sebastian Pepper!
&lt;/p&gt;
</code></pre>

<p>obtains the user name by executing:</p>

<pre><code>  ((User) ctx.getVariable(&quot;session&quot;).get(&quot;user&quot;)).getName();
</code></pre>

<p>But getter method navigation is just one of OGNL’s features. Let’s see some more:</p>

<pre><code class="language-js">/*
 * Access to properties using the point (.). Equivalent to calling property getters.
 */
${person.father.name}

/*
 * Access to properties can also be made by using brackets ([]) and writing 
 * the name of the property as a variable or between single quotes.
 */
${person['father']['name']}

/*
 * If the object is a map, both dot and bracket syntax will be equivalent to 
 * executing a call on its get(...) method.
 */
${countriesByCode.ES}
${personsByName['Stephen Zucchini'].age}

/*
 * Indexed access to arrays or collections is also performed with brackets, 
 * writing the index without quotes.
 */
${personsArray[0].name}

/*
 * Methods can be called, even with arguments.
 */
${person.createCompleteName()}
${person.createCompleteNameWithSeparator('-')}
</code></pre>

<p><strong>Expression Basic Objects</strong></p>

<p>When evaluating OGNL expressions on the context variables, some objects are made available to expressions for higher flexibility. These objects will be referenced (per OGNL standard) starting with the # symbol:</p>

<pre><code>#ctx: the context object.
#vars: the context variables.
#locale: the context locale.
#request: (only in Web Contexts) the HttpServletRequest object.
#response: (only in Web Contexts) the HttpServletResponse object.
#session: (only in Web Contexts) the HttpSession object.
#servletContext: (only in Web Contexts) the ServletContext object.
</code></pre>

<p>So we can do this:</p>

<p>Established locale country: <code>&lt;span th:text=&quot;${#locale.country}&quot;&gt;US&lt;/span&gt;</code>.</p>

<p>You can read the full reference of these objects in Appendix A.
Expression Utility Objects</p>

<p>Besides these basic objects, Thymeleaf will offer us a set of utility objects that will help us perform common tasks in our expressions.</p>

<pre><code>#execInfo: information about the template being processed.
#messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
#uris: methods for escaping parts of URLs/URIs
#conversions: methods for executing the configured conversion service (if any).
#dates: methods for java.util.Date objects: formatting, component extraction, etc.
#calendars: analogous to #dates, but for java.util.Calendar objects.
#numbers: methods for formatting numeric objects.
#strings: methods for String objects: contains, startsWith, prepending/appending, etc.
#objects: methods for objects in general.
#bools: methods for boolean evaluation.
#arrays: methods for arrays.
#lists: methods for lists.
#sets: methods for sets.
#maps: methods for maps.
#aggregates: methods for creating aggregates on arrays or collections.
#ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
</code></pre>

<p>You can check what functions are offered by each of these utility objects in the Appendix B.</p>

<p><strong>Reformatting dates in our home page</strong></p>

<p>Now we know about these utility objects, we could use them to change the way in which we show the date in our home page. Instead of doing this in our HomeController:</p>

<pre><code class="language-java">SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;dd MMMM yyyy&quot;);
Calendar cal = Calendar.getInstance();

WebContext ctx = new WebContext(request, servletContext, request.getLocale());
ctx.setVariable(&quot;today&quot;, dateFormat.format(cal.getTime()));

templateEngine.process(&quot;home&quot;, ctx, response.getWriter());
</code></pre>

<p>we can do just this:</p>

<pre><code class="language-java">WebContext ctx = 
    new WebContext(request, response, servletContext, request.getLocale());
ctx.setVariable(&quot;today&quot;, Calendar.getInstance());

templateEngine.process(&quot;home&quot;, ctx, response.getWriter());
</code></pre>

<p>and then perform date formatting in the view layer itself:</p>

<pre><code class="language-html">&lt;p&gt;
  Today is: &lt;span th:text=&quot;${#calendars.format(today,'dd MMMM yyyy')}&quot;&gt;13 May 2011&lt;/span&gt;
&lt;/p&gt;
</code></pre>

<h2 id="4-3-expressions-on-selections-asterisk-syntax">4.3. Expressions on selections (asterisk syntax)</h2>

<p>Not only can variable expressions be written as <code>${...}</code>, but also as <code>*{...}</code>.</p>

<p>There is an important difference though: the asterisk syntax evaluates expressions on selected objects rather than on the whole context. That is, as long as there is no selected object, the dollar and the asterisk syntaxes do exactly the same.</p>

<p>And what is a selected object? The result of an expression using the th:object attribute. Let’s use one in our user profile (userprofile.html) page:</p>

<pre><code class="language-html">  &lt;div th:object=&quot;${session.user}&quot;&gt;
    &lt;p&gt;Name: &lt;span th:text=&quot;*{firstName}&quot;&gt;Sebastian&lt;/span&gt;.&lt;/p&gt;
    &lt;p&gt;Surname: &lt;span th:text=&quot;*{lastName}&quot;&gt;Pepper&lt;/span&gt;.&lt;/p&gt;
    &lt;p&gt;Nationality: &lt;span th:text=&quot;*{nationality}&quot;&gt;Saturn&lt;/span&gt;.&lt;/p&gt;
  &lt;/div&gt;
</code></pre>

<p>Which is exactly equivalent to:</p>

<pre><code class="language-html">&lt;div&gt;
  &lt;p&gt;Name: &lt;span th:text=&quot;${session.user.firstName}&quot;&gt;Sebastian&lt;/span&gt;.&lt;/p&gt;
  &lt;p&gt;Surname: &lt;span th:text=&quot;${session.user.lastName}&quot;&gt;Pepper&lt;/span&gt;.&lt;/p&gt;
  &lt;p&gt;Nationality: &lt;span th:text=&quot;${session.user.nationality}&quot;&gt;Saturn&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
</code></pre>

<p>Of course, dollar and asterisk syntax can be mixed:</p>

<pre><code class="language-html">&lt;div th:object=&quot;${session.user}&quot;&gt;
  &lt;p&gt;Name: &lt;span th:text=&quot;*{firstName}&quot;&gt;Sebastian&lt;/span&gt;.&lt;/p&gt;
  &lt;p&gt;Surname: &lt;span th:text=&quot;${session.user.lastName}&quot;&gt;Pepper&lt;/span&gt;.&lt;/p&gt;
  &lt;p&gt;Nationality: &lt;span th:text=&quot;*{nationality}&quot;&gt;Saturn&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
</code></pre>

<p>When an object selection is in place, the selected object will also be available to dollar expressions as the <code>#object</code> expression variable:</p>

<pre><code class="language-html">&lt;div th:object=&quot;${session.user}&quot;&gt;
  &lt;p&gt;Name: &lt;span th:text=&quot;${#object.firstName}&quot;&gt;Sebastian&lt;/span&gt;.&lt;/p&gt;
  &lt;p&gt;Surname: &lt;span th:text=&quot;${session.user.lastName}&quot;&gt;Pepper&lt;/span&gt;.&lt;/p&gt;
  &lt;p&gt;Nationality: &lt;span th:text=&quot;*{nationality}&quot;&gt;Saturn&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
</code></pre>

<p>As said, if no object selection has been performed, dollar and asterisk syntaxes are equivalent.</p>

<pre><code class="language-html">&lt;div&gt;
  &lt;p&gt;Name: &lt;span th:text=&quot;*{session.user.name}&quot;&gt;Sebastian&lt;/span&gt;.&lt;/p&gt;
  &lt;p&gt;Surname: &lt;span th:text=&quot;*{session.user.surname}&quot;&gt;Pepper&lt;/span&gt;.&lt;/p&gt;
  &lt;p&gt;Nationality: &lt;span th:text=&quot;*{session.user.nationality}&quot;&gt;Saturn&lt;/span&gt;.&lt;/p&gt;
&lt;/div&gt;
</code></pre>

<h2 id="4-4-link-urls">4.4. Link URLs</h2>

<p>Because of their importance, URLs are first-class citizens in web application templates, and the Thymeleaf Standard Dialect has a special syntax for them, the @ syntax: <code>@{...}</code></p>

<p>There are different types of URLs:</p>

<pre><code>Absolute URLs: http://www.thymeleaf.org
Relative URLs, which can be:
    Page-relative: user/login.html
    Context-relative: /itemdetails?id=3 (context name in server will be added automatically)
    Server-relative: ~/billing/processInvoice (allows calling URLs in another context (= application) in the same server.
    Protocol-relative URLs: //code.jquery.com/jquery-2.0.3.min.js
</code></pre>

<p>The real processing of these expressions and their conversion to the URLs that will be output is done by implementations of the <code>org.thymeleaf.linkbuilder.ILinkBuilder</code> interface that are registered into the ITemplateEngine object being used.</p>

<p>By default, a single implementation of this interface is registered of the class org.thymeleaf.linkbuilder.StandardLinkBuilder, which is enough for both offline (non-web) and also web scenarios based on the Servlet API. Other scenarios (like integration with non-ServletAPI web frameworks) might need specific implementations of the link builder interface.</p>

<p>Let’s use this new syntax. Meet the th:href attribute:</p>

<pre><code class="language-html">&lt;!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) --&gt;
&lt;a href=&quot;details.html&quot; 
   th:href=&quot;@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}&quot;&gt;view&lt;/a&gt;

&lt;!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) --&gt;
&lt;a href=&quot;details.html&quot; th:href=&quot;@{/order/details(orderId=${o.id})}&quot;&gt;view&lt;/a&gt;

&lt;!-- Will produce '/gtvg/order/3/details' (plus rewriting) --&gt;
&lt;a href=&quot;details.html&quot; th:href=&quot;@{/order/{orderId}/details(orderId=${o.id})}&quot;&gt;view&lt;/a&gt;
</code></pre>

<p>Some things to note here:</p>

<pre><code>th:href is a modifier attribute: once processed, it will compute the link URL to be used and set that value to the href attribute of the &lt;a&gt; tag.
We are allowed to use expressions for URL parameters (as you can see in orderId=${o.id}). The required URL-parameter-encoding operations will also be automatically performed.
If several parameters are needed, these will be separated by commas: @{/order/process(execId=${execId},execType='FAST')}
Variable templates are also allowed in URL paths: @{/order/{orderId}/details(orderId=${orderId})}
Relative URLs starting with / (eg: /order/details) will be automatically prefixed by the application context name.
If cookies are not enabled or this is not yet known, a &quot;;jsessionid=...&quot; suffix might be added to relative URLs so that the session is preserved. This is called URL Rewriting and Thymeleaf allows you to plug in your own rewriting filters by using the response.encodeURL(...) mechanism from the Servlet API for every URL.
The th:href attribute allows us to (optionally) have a working static href attribute in our template, so that our template links remained navigable by a browser when opened directly for prototyping purposes.
</code></pre>

<p>As was the case with the message syntax (<code>#{...}</code>), URL bases can also be the result of evaluating another expression:</p>

<pre><code class="language-html">&lt;a th:href=&quot;@{${url}(orderId=${o.id})}&quot;&gt;view&lt;/a&gt;
&lt;a th:href=&quot;@{'/details/'+${user.login}(orderId=${o.id})}&quot;&gt;view&lt;/a&gt;
</code></pre>

<p><strong>A menu for our home page</strong></p>

<p>Now that we know how to create link URLs, what about adding a small menu in our home page for some of the other pages in the site?</p>

<pre><code class="language-html">&lt;p&gt;Please select an option&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;product/list.html&quot; th:href=&quot;@{/product/list}&quot;&gt;Product List&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;order/list.html&quot; th:href=&quot;@{/order/list}&quot;&gt;Order List&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;subscribe.html&quot; th:href=&quot;@{/subscribe}&quot;&gt;Subscribe to our Newsletter&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;userprofile.html&quot; th:href=&quot;@{/userprofile}&quot;&gt;See User Profile&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
</code></pre>

<p><strong>Server root relative URLs</strong></p>

<p>An additional syntax can be used to create server-root-relative (instead of context-root-relative) URLs in order to link to different contexts in the same server. These URLs will be specified like <code>@{~/path/to/something}</code></p>

<h2 id="4-5-fragments">4.5. Fragments</h2>

<p>Fragment expressions are an easy way to represent fragments of markup and move them around templates. This allows us to replicate them, pass them to other templates as arguments, and so on.</p>

<p>The most common use is for fragment insertion using <code>th:insert</code> or <code>th:replace</code> (more on these in a later section):</p>

<pre><code class="language-html">&lt;div th:insert=&quot;~{commons :: main}&quot;&gt;...&lt;/div&gt;
</code></pre>

<p>But they can be used anywhere, just as any other variable:</p>

<div th:with="frag=~{footer :: #main/text()}">
  <p th:insert="${frag}">
</div>

<p>Later in this tutorial there is an entire section devoted to Template Layout, including deeper explanation of fragment expressions.
4.6 Literals
Text literals</p>

<p>Text literals are just character strings specified between single quotes. They can include any character, but you should escape any single quotes inside them using \&lsquo;.</p>

<p>
  Now you are looking at a <span th:text="'working web application'">template file</span>.
</p>

<p>Number literals</p>

<p>Numeric literals are just that: numbers.</p>

<p>The year is <span th:text="2013">1492</span>.</p>
<p>In two years, it will be <span th:text="2013 + 2">1494</span>.</p>

<p>Boolean literals</p>

<p>The boolean literals are true and false. For example:</p>

<div th:if="${user.isAdmin()} == false"> ...

In this example, the == false is written outside the braces, and so it is Thymeleaf that takes care of it. If it were written inside the braces, it would be the responsibility of the OGNL/SpringEL engines:

<div th:if="${user.isAdmin() == false}"> ...

The null literal

The null literal can be also used:

<div th:if="${variable.something} == null"> ...

Literal tokens

Numeric, boolean and null literals are in fact a particular case of literal tokens.

These tokens allow a little bit of simplification in Standard Expressions. They work exactly the same as text literals ('...'), but they only allow letters (A-Z and a-z), numbers (0-9), brackets ([ and ]), dots (.), hyphens (-) and underscores (_). So no whitespaces, no commas, etc.

The nice part? Tokens don’t need any quotes surrounding them. So we can do this:

<div th:class="content">...</div>

<p>instead of:</p>

<div th:class="'content'">...</div>

<p>4.7 Appending texts</p>

<p>Texts, no matter whether they are literals or the result of evaluating variable or message expressions, can be easily appended using the + operator:</p>

<p><span th:text="'The name of the user is ' + ${user.name}"></p>

<p>4.8 Literal substitutions</p>

<p>Literal substitutions allow for an easy formatting of strings containing values from variables without the need to append literals with &lsquo;&hellip;&rsquo; + &lsquo;&hellip;&rsquo;.</p>

<p>These substitutions must be surrounded by vertical bars (|), like:</p>

<p><span th:text="|Welcome to our application, ${user.name}!|"></p>

<p>Which is equivalent to:</p>

<p><span th:text="'Welcome to our application, ' + ${user.name} + '!'"></p>

<p>Literal substitutions can be combined with other types of expressions:</p>

<p><span th:text="${onevar} + ' ' + |${twovar}, ${threevar}|"></p>

<pre><code>Only variable/message expressions (${...}, *{...}, #{...}) are allowed inside |...| literal substitutions. No other literals ('...'), boolean/numeric tokens, conditional expressions etc. are.
</code></pre>

<p>4.9 Arithmetic operations</p>

<p>Some arithmetic operations are also available: +, -, *, / and %.</p>

<div th:with="isEven=(${prodStat.count} % 2 == 0)">

Note that these operators can also be applied inside OGNL variable expressions themselves (and in that case will be executed by OGNL instead of the Thymeleaf Standard Expression engine):

<div th:with="isEven=${prodStat.count % 2 == 0}">

Note that textual aliases exist for some of these operators: div (/), mod (%).
4.10 Comparators and Equality

Values in expressions can be compared with the >, <, >= and <= symbols, and the == and != operators can be used to check for equality (or the lack of it). Note that XML establishes that the < and > symbols should not be used in attribute values, and so they should be substituted by &lt; and &gt;.

<div th:if="${prodStat.count} &gt; 1">
<span th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')">

A simpler alternative may be using textual aliases that exist for some of these operators: gt (>), lt (<), ge (>=), le (<=), not (!). Also eq (==), neq/ne (!=).
4.11 Conditional expressions

Conditional expressions are meant to evaluate only one of two expressions depending on the result of evaluating a condition (which is itself another expression).

Let’s have a look at an example fragment (introducing another attribute modifier, th:class):

<tr th:class="${row.even}? 'even' : 'odd'">
  ...
</tr>

All three parts of a conditional expression (condition, then and else) are themselves expressions, which means that they can be variables (${...}, *{...}), messages (#{...}), URLs (@{...}) or literals ('...').

Conditional expressions can also be nested using parentheses:

<tr th:class="${row.even}? (${row.first}? 'first' : 'even') : 'odd'">
  ...
</tr>

Else expressions can also be omitted, in which case a null value is returned if the condition is false:

<tr th:class="${row.even}? 'alt'">
  ...
</tr>

4.12 Default expressions (Elvis operator)

A default expression is a special kind of conditional value without a then part. It is equivalent to the Elvis operator present in some languages like Groovy, lets you specify two expressions: the first one is used if it doesn’t evaluate to null, but if it does then the second one is used.

Let’s see it in action in our user profile page:

<div th:object="${session.user}">
  ...
  <p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p>
</div>

<p>As you can see, the operator is ?:, and we use it here to specify a default value for a name (a literal value, in this case) only if the result of evaluating *{age} is null. This is therefore equivalent to:</p>

<p>Age: <span th:text="*{age != null}? *{age} : '(no age specified)'">27</span>.</p>

<p>As with conditional values, they can contain nested expressions between parentheses:</p>

<p>
  Name: 
  <span th:text="*{firstName}?: (*{admin}? 'Admin' : #{default.username})">Sebastian</span>
</p>

<p>4.13 The No-Operation token</p>

<p>The No-Operation token is represented by an underscore symbol (_).</p>

<p>The idea behind this token is to specify that the desired result for an expression is to do nothing, i.e. do exactly as if the processable attribute (e.g. th:text) was not there at all.</p>

<p>Among other possibilities, this allows developers to use prototyping text as default values. For example, instead of:</p>

<p><span th:text="${user.name} ?: 'no user authenticated'">&hellip;</span></p>

<p>…we can directly use ‘no user authenticated’ as a prototyping text, which results in code that is both more concise and versatile from a design standpoint:</p>

<p><span th:text="${user.name} ?: _">no user authenticated</span></p>

<p>4.14 Data Conversion / Formatting</p>

<p>Thymeleaf defines a double-brace syntax for variable (${&hellip;}) and selection (*{&hellip;}) expressions that allows us to apply data conversion by means of a configured conversion service.</p>

<p>It basically goes like this:</p>

<p><td th:text="${{user.lastAccessDate}}">&hellip;</td></p>

<p>Noticed the double brace there?: ${{&hellip;}}. That instructs Thymeleaf to pass the result of the user.lastAccessDate expression to the conversion service and asks it to perform a formatting operation (a conversion to String) before writing the result.</p>

<p>Assuming that user.lastAccessDate is of type java.util.Calendar, if a conversion service (implementation of IStandardConversionService) has been registered and contains a valid conversion for Calendar -&gt; String, it will be applied.</p>

<p>The default implementation of IStandardConversionService (the StandardConversionService class) simply executes .toString() on any object converted to String. For more information on how to register a custom conversion service implementation, have a look at the More on Configuration section.</p>

<pre><code>The official thymeleaf-spring3 and thymeleaf-spring4 integration packages transparently integrate Thymeleaf’s conversion service mechanism with Spring’s own Conversion Service infrastructure, so that conversion services and formatters declared in the Spring configuration will be made automatically available to ${{...}} and *{{...}} expressions.
</code></pre>

<p>4.15 Preprocessing</p>

<p>In addition to all these features for expression processing, Thymeleaf has the feature of preprocessing expressions.</p>

<p>Preprocessing is an execution of the expressions done before the normal one that allows for modification of the expression that will eventually be executed.</p>

<p>Preprocessed expressions are exactly like normal ones, but appear surrounded by a double underscore symbol (like <strong>${expression}</strong>).</p>

<p>Let’s imagine we have an i18n Messages_fr.properties entry containing an OGNL expression calling a language-specific static method, like:</p>

<p>article.text=@myapp.translator.Translator@translateToFrench({0})</p>

<p>…and a Messages_es.properties equivalent:</p>

<p>article.text=@myapp.translator.Translator@translateToSpanish({0})</p>

<p>We can create a fragment of markup that evaluates one expression or the other depending on the locale. For this, we will first select the expression (by preprocessing) and then let Thymeleaf execute it:</p>

<p th:text="${__#{article.text('textVar')}__}">Some text here...</p>

<p>Note that the preprocessing step for a French locale will be creating the following equivalent:</p>

<p th:text="${@myapp.translator.Translator@translateToFrench(textVar)}">Some text here...</p>

<p>The preprocessing String __ can be escaped in attributes using __.
5 Setting Attribute Values</p>

<p>This chapter will explain the way in which we can set (or modify) values of attributes in our markup.
5.1 Setting the value of any attribute</p>

<p>Say our website publishes a newsletter, and we want our users to be able to subscribe to it, so we create a /WEB-INF/templates/subscribe.html template with a form:</p>

<form action="subscribe.html">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" />
  </fieldset>
</form>

<p>As with Thymeleaf, this template starts off more like a static prototype than it does a template for a web application. First, the action attribute in our form statically links to the template file itself, so that there is no place for useful URL rewriting. Second, the value attribute in the submit button makes it display a text in English, but we’d like it to be internationalized.</p>

<p>Enter then the th:attr attribute, and its ability to change the value of attributes of the tags it is set in:</p>

<form action="subscribe.html" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  </fieldset>
</form>

<p>The concept is quite straightforward: th:attr simply takes an expression that assigns a value to an attribute. Having created the corresponding controller and messages files, the result of processing this file will be:</p>

<form action="/gtvg/subscribe">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="¡Suscríbe!"/>
  </fieldset>
</form>

<p>Besides the new attribute values, you can also see that the applicacion context name has been automatically prefixed to the URL base in /gtvg/subscribe, as explained in the previous chapter.</p>

<p>But what if we wanted to set more than one attribute at a time? XML rules do not allow you to set an attribute twice in a tag, so th:attr will take a comma-separated list of assignments, like:</p>

<p><img src="../../images/gtvglogo.png" 
     th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" /></p>

<p>Given the required messages files, this will output:</p>

<p><img src="/gtgv/images/gtvglogo.png" title="Logo de Good Thymes" alt="Logo de Good Thymes" /></p>

<p>5.2 Setting value to specific attributes</p>

<p>By now, you might be thinking that something like:</p>

<p><input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/></p>

<p>…is quite an ugly piece of markup. Specifying an assignment inside an attribute’s value can be very practical, but it is not the most elegant way of creating templates if you have to do it all the time.</p>

<p>Thymeleaf agrees with you, and that’s why th:attr is scarcely used in templates. Normally, you will be using other th:* attributes whose task is setting specific tag attributes (and not just any attribute like th:attr).</p>

<p>For example, to set the value attribute, use th:value:</p>

<p><input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/></p>

<p>This looks much better! Let’s try and do the same to the action attribute in the form tag:</p>

<p><form action="subscribe.html" th:action="@{/subscribe}"></p>

<p>And do you remember those th:href we put in our home.html before? They are exactly this same kind of attributes:</p>

<p><li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li></p>

<p>There are quite a lot of attributes like these, each of them targeting a specific HTML5 attribute:
th:abbr     th:accept   th:accept-charset
th:accesskey    th:action   th:align
th:alt  th:archive  th:audio
th:autocomplete     th:axis     th:background
th:bgcolor  th:border   th:cellpadding
th:cellspacing  th:challenge    th:charset
th:cite     th:class    th:classid
th:codebase     th:codetype     th:cols
th:colspan  th:compact  th:content
th:contenteditable  th:contextmenu  th:data
th:datetime     th:dir  th:draggable
th:dropzone     th:enctype  th:for
th:form     th:formaction   th:formenctype
th:formmethod   th:formtarget   th:fragment
th:frame    th:frameborder  th:headers
th:height   th:high     th:href
th:hreflang     th:hspace   th:http-equiv
th:icon     th:id   th:inline
th:keytype  th:kind     th:label
th:lang     th:list     th:longdesc
th:low  th:manifest     th:marginheight
th:marginwidth  th:max  th:maxlength
th:media    th:method   th:min
th:name     th:onabort  th:onafterprint
th:onbeforeprint    th:onbeforeunload   th:onblur
th:oncanplay    th:oncanplaythrough     th:onchange
th:onclick  th:oncontextmenu    th:ondblclick
th:ondrag   th:ondragend    th:ondragenter
th:ondragleave  th:ondragover   th:ondragstart
th:ondrop   th:ondurationchange     th:onemptied
th:onended  th:onerror  th:onfocus
th:onformchange     th:onforminput  th:onhashchange
th:oninput  th:oninvalid    th:onkeydown
th:onkeypress   th:onkeyup  th:onload
th:onloadeddata     th:onloadedmetadata     th:onloadstart
th:onmessage    th:onmousedown  th:onmousemove
th:onmouseout   th:onmouseover  th:onmouseup
th:onmousewheel     th:onoffline    th:ononline
th:onpause  th:onplay   th:onplaying
th:onpopstate   th:onprogress   th:onratechange
th:onreadystatechange   th:onredo   th:onreset
th:onresize     th:onscroll     th:onseeked
th:onseeking    th:onselect     th:onshow
th:onstalled    th:onstorage    th:onsubmit
th:onsuspend    th:ontimeupdate     th:onundo
th:onunload     th:onvolumechange   th:onwaiting
th:optimum  th:pattern  th:placeholder
th:poster   th:preload  th:radiogroup
th:rel  th:rev  th:rows
th:rowspan  th:rules    th:sandbox
th:scheme   th:scope    th:scrolling
th:size     th:sizes    th:span
th:spellcheck   th:src  th:srclang
th:standby  th:start    th:step
th:style    th:summary  th:tabindex
th:target   th:title    th:type
th:usemap   th:value    th:valuetype
th:vspace   th:width    th:wrap
th:xmlbase  th:xmllang  th:xmlspace
5.3 Setting more than one value at a time</p>

<p>There are two rather special attributes called th:alt-title and th:lang-xmllang which can be used for setting two attributes to the same value at the same time. Specifically:</p>

<pre><code>th:alt-title will set alt and title.
th:lang-xmllang will set lang and xml:lang.
</code></pre>

<p>For our GTVG home page, this will allow us to substitute this:</p>

<p><img src="../../images/gtvglogo.png" 
     th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" /></p>

<p>…or this, which is equivalent:</p>

<p><img src="../../images/gtvglogo.png" 
     th:src="@{/images/gtvglogo.png}" th:title="#{logo}" th:alt="#{logo}" /></p>

<p>…with this:</p>

<p><img src="../../images/gtvglogo.png" 
     th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" /></p>

<p>5.4 Appending and prepending</p>

<p>Thymeleaf also offers the th:attrappend and th:attrprepend attributes, which append (suffix) or prepend (prefix) the result of their evaluation to the existing attribute values.</p>

<p>For example, you might want to store the name of a CSS class to be added (not set, just added) to one of your buttons in a context variable, because the specific CSS class to be used would depend on something that the user did before:</p>

<p><input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" /></p>

<p>If you process this template with the cssStyle variable set to &ldquo;warning&rdquo;, you will get:</p>

<p><input type="button" value="Do it!" class="btn warning" /></p>

<p>There are also two specific appending attributes in the Standard Dialect: the th:classappend and th:styleappend attributes, which are used for adding a CSS class or a fragment of style to an element without overwriting the existing ones:</p>

<p><tr th:each="prod : ${prods}" class="row" th:classappend="${prodStat.odd}? 'odd'"></p>

<p>(Don’t worry about that th:each attribute. It is an iterating attribute and we will talk about it later.)
5.5 Fixed-value boolean attributes</p>

<p>HTML has the concept of boolean attributes, attributes that have no value and the prescence of one means that value is “true”. In XHTML, these attributes take just 1 value, which is itself.</p>

<p>For example, checked:</p>

<p><input type="checkbox" name="option2" checked /> <!-- HTML -->
<input type="checkbox" name="option1" checked="checked" /> <!-- XHTML --></p>

<p>The Standard Dialect includes attributes that allow you to set these attributes by evaluating a condition, so that if evaluated to true, the attribute will be set to its fixed value, and if evaluated to false, the attribute will not be set:</p>

<p><input type="checkbox" name="active" th:checked="${user.active}" /></p>

<p>The following fixed-value boolean attributes exist in the Standard Dialect:
th:async    th:autofocus    th:autoplay
th:checked  th:controls     th:declare
th:default  th:defer    th:disabled
th:formnovalidate   th:hidden   th:ismap
th:loop     th:multiple     th:novalidate
th:nowrap   th:open     th:pubdate
th:readonly     th:required     th:reversed
th:scoped   th:seamless     th:selected
5.6 Setting the value of any attribute (default attribute processor)</p>

<p>Thymeleaf offers a default attribute processor that allows us to set the value of any attribute, even if no specific th:* processor has been defined for it at the Standard Dialect.</p>

<p>So something like:</p>

<p><span th:whatever="${user.name}">&hellip;</span></p>

<p>Will result in:</p>

<p><span whatever="John Apricot">&hellip;</span></p>

<p>5.7 Support for HTML5-friendly attribute and element names</p>

<p>It is also possible to use a completely different syntax to apply processors to your templates in a more HTML5-friendly manner.</p>

<table>
    <tr data-th-each="user : ${users}">
        <td data-th-text="${user.login}">...</td>
        <td data-th-text="${user.name}">...</td>
    </tr>
</table>

<p>The data-{prefix}-{name} syntax is the standard way to write custom attributes in HTML5, without requiring developers to use any namespaced names like th:*. Thymeleaf makes this syntax automatically available to all your dialects (not only the Standard ones).</p>

<p>There is also a syntax to specify custom tags: {prefix}-{name}, which follows the W3C Custom Elements specification (a part of the larger W3C Web Components spec). This can be used, for example, for the th:block element (or also th-block), which will be explained in a later section.</p>

<p>Important: this syntax is an addition to the namespaced th:* one, it does not replace it. There is no intention at all to deprecate the namespaced syntax in the future.
6 Iteration</p>

<p>So far we have created a home page, a user profile page and also a page for letting users subscribe to our newsletter… but what about our products? For that, we will need a way to iterate over items in a collection to build out our product page.
6.1 Iteration basics</p>

<p>To display products in our /WEB-INF/templates/product/list.html page we will use a table. Each of our products will be displayed in a row (a <tr> element), and so for our template we will need to create a template row – one that will exemplify how we want each product to be displayed – and then instruct Thymeleaf to repeat it, once for each product.</p>

<p>The Standard Dialect offers us an attribute for exactly that: th:each.
Using th:each</p>

<p>For our product list page, we will need a controller method that retrieves the list of products from the service layer and adds it to the template context:</p>

<p>public void process(
        final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext servletContext, final ITemplateEngine templateEngine)
        throws Exception {</p>

<pre><code>ProductService productService = new ProductService();
List&lt;Product&gt; allProducts = productService.findAll(); 

WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
ctx.setVariable(&quot;prods&quot;, allProducts);

templateEngine.process(&quot;product/list&quot;, ctx, response.getWriter());
</code></pre>

<p>}</p>

<p>And then we will use th:each in our template to iterate over the list of products:</p>

<p>&lt;!DOCTYPE html&gt;</p>

<p><html xmlns:th="http://www.thymeleaf.org"></p>

<p><head>
    <title>Good Thymes Virtual Grocery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all" 
          href="../../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  </head></p>

<p><body></p>

<pre><code>&lt;h1&gt;Product list&lt;/h1&gt;

&lt;table&gt;
  &lt;tr&gt;
    &lt;th&gt;NAME&lt;/th&gt;
    &lt;th&gt;PRICE&lt;/th&gt;
    &lt;th&gt;IN STOCK&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr th:each=&quot;prod : ${prods}&quot;&gt;
    &lt;td th:text=&quot;${prod.name}&quot;&gt;Onions&lt;/td&gt;
    &lt;td th:text=&quot;${prod.price}&quot;&gt;2.41&lt;/td&gt;
    &lt;td th:text=&quot;${prod.inStock}? #{true} : #{false}&quot;&gt;yes&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;
  &lt;a href=&quot;../home.html&quot; th:href=&quot;@{/}&quot;&gt;Return to home&lt;/a&gt;
&lt;/p&gt;
</code></pre>

<p></body></p>

<p></html></p>

<p>That prod : ${prods} attribute value you see above means “for each element in the result of evaluating ${prods}, repeat this fragment of template, using the current element in a variable called prod”. Let’s give a name each of the things we see:</p>

<pre><code>We will call ${prods} the iterated expression or iterated variable.
We will call prod the iteration variable or simply iter variable.
</code></pre>

<p>Note that the prod iter variable is scoped to the <tr> element, which means it is available to inner tags like <td>.
Iterable values</p>

<p>The java.util.List class isn’t the onlyvalue that can be used for iteration in Thymeleaf. There is a quite complete set of objects that are considered iterable by a th:each attribute:</p>

<pre><code>Any object implementing java.util.Iterable
Any object implementing java.util.Enumeration.
Any object implementing java.util.Iterator, whose values will be used as they are returned by the iterator, without the need to cache all values in memory.
Any object implementing java.util.Map. When iterating maps, iter variables will be of class java.util.Map.Entry.
Any array.
Any other object will be treated as if it were a single-valued list containing the object itself.
</code></pre>

<p>6.2 Keeping iteration status</p>

<p>When using th:each, Thymeleaf offers a mechanism useful for keeping track of the status of your iteration: the status variable.</p>

<p>Status variables are defined within a th:each attribute and contain the following data:</p>

<pre><code>The current iteration index, starting with 0. This is the index property.
The current iteration index, starting with 1. This is the count property.
The total amount of elements in the iterated variable. This is the size property.
The iter variable for each iteration. This is the current property.
Whether the current iteration is even or odd. These are the even/odd boolean properties.
Whether the current iteration is the first one. This is the first boolean property.
Whether the current iteration is the last one. This is the last boolean property.
</code></pre>

<p>Let’s see how we could use it with the previous example:</p>

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
  </tr>
  <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>
</table>

<p>The status variable (iterStat in this example) is defined in the th:each attribute by writing its name after the iter variable itself, separated by a comma. Just like the iter variable, the status variable is also scoped to the fragment of code defined by the tag holding the th:each attribute.</p>

<p>Let’s have a look at the result of processing our template:</p>

<p>&lt;!DOCTYPE html&gt;</p>

<p><html></p>

<p><head>
    <title>Good Thymes Virtual Grocery</title>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    <link rel="stylesheet" type="text/css" media="all" href="/gtvg/css/gtvg.css" />
  </head></p>

<p><body></p>

<pre><code>&lt;h1&gt;Product list&lt;/h1&gt;

&lt;table&gt;
  &lt;tr&gt;
    &lt;th&gt;NAME&lt;/th&gt;
    &lt;th&gt;PRICE&lt;/th&gt;
    &lt;th&gt;IN STOCK&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr class=&quot;odd&quot;&gt;
    &lt;td&gt;Fresh Sweet Basil&lt;/td&gt;
    &lt;td&gt;4.99&lt;/td&gt;
    &lt;td&gt;yes&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Italian Tomato&lt;/td&gt;
    &lt;td&gt;1.25&lt;/td&gt;
    &lt;td&gt;no&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr class=&quot;odd&quot;&gt;
    &lt;td&gt;Yellow Bell Pepper&lt;/td&gt;
    &lt;td&gt;2.50&lt;/td&gt;
    &lt;td&gt;yes&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;Old Cheddar&lt;/td&gt;
    &lt;td&gt;18.75&lt;/td&gt;
    &lt;td&gt;yes&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;
  &lt;a href=&quot;/gtvg/&quot; shape=&quot;rect&quot;&gt;Return to home&lt;/a&gt;
&lt;/p&gt;
</code></pre>

<p></body></p>

<p></html></p>

<p>Note that our iteration status variable has worked perfectly, establishing the odd CSS class only to odd rows.</p>

<p>If you don’t explicitly set a status variable, Thymeleaf will always create one for you by suffixing Stat to the name of the iteration variable:</p>

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>
</table>

<p>6.3 Optimizing through lazy retrieval of data</p>

<p>Sometimes we might want to optimize the retrieval of collections of data ( e.g. from a database) so that these collections are only retrieved if they are really going to be used.</p>

<pre><code>Actually, this is something that can be applied to any piece of data, but given the size that in-memory collections might have, retrieving collections that are meant to be iterated is the most common case for this scenario.
</code></pre>

<p>In order to support this, Thymeleaf offers a mechanism to lazily load context variables. Context variables that implement the ILazyContextVariable interface – most probably by extending its LazyContextVariable default implementation – will be resolved in the moment of being executed. For example:</p>

<p>context.setVariable(
     &ldquo;users&rdquo;,
     new LazyContextVariable<List<User>&gt;() {
         @Override
         protected List<User> loadValue() {
             return databaseRepository.findAllUsers();
         }
     });</p>

<p>This variable can be used without knowledge of its lazyness, in code such as:</p>

<ul>
  <li th:each="u : ${users}" th:text="${u.name}">user name</li>
</ul>

<p>But at the same time, will never be initialized (its loadValue() method will never be called) if condition evaluates to false in code such as:</p>

<ul th:if="${condition}">
  <li th:each="u : ${users}" th:text="${u.name}">user name</li>
</ul>

<p>7 Conditional Evaluation
7.1 Simple conditionals: “if” and “unless”</p>

<p>Sometimes you will need a fragment of your template to only appear in the result if a certain condition is met.</p>

<p>For example, imagine we want to show in our product table a column with the number of comments that exist for each product and, if there are any comments, a link to the comment detail page for that product.</p>

<p>In order to do this, we would use the th:if attribute:</p>

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    <td>
      <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
      <a href="comments.html" 
         th:href="@{/product/comments(prodId=${prod.id})}" 
         th:if="${not #lists.isEmpty(prod.comments)}">view</a>
    </td>
  </tr>
</table>

<p>Quite a lot of things to see here, so let’s focus on the important line:</p>

<p><a href="comments.html"
   th:href="@{/product/comments(prodId=${prod.id})}" 
   th:if="${not #lists.isEmpty(prod.comments)}">view</a></p>

<p>This will create a link to the comments page (with URL /product/comments) with a prodId parameter set to the id of the product, but only if the product has any comments.</p>

<p>Let’s have a look at the resulting markup:</p>

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr>
    <td>Fresh Sweet Basil</td>
    <td>4.99</td>
    <td>yes</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr class="odd">
    <td>Italian Tomato</td>
    <td>1.25</td>
    <td>no</td>
    <td>
      <span>2</span> comment/s
      <a href="/gtvg/product/comments?prodId=2">view</a>
    </td>
  </tr>
  <tr>
    <td>Yellow Bell Pepper</td>
    <td>2.50</td>
    <td>yes</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr class="odd">
    <td>Old Cheddar</td>
    <td>18.75</td>
    <td>yes</td>
    <td>
      <span>1</span> comment/s
      <a href="/gtvg/product/comments?prodId=4">view</a>
    </td>
  </tr>
</table>

<p>Perfect! That’s exactly what we wanted.</p>

<p>Note that the th:if attribute will not only evaluate boolean conditions. Its capabilities go a little beyond that, and it will evaluate the specified expression as true following these rules:</p>

<pre><code>If value is not null:
    If value is a boolean and is true.
    If value is a number and is non-zero
    If value is a character and is non-zero
    If value is a String and is not “false”, “off” or “no”
    If value is not a boolean, a number, a character or a String.
(If value is null, th:if will evaluate to false).
</code></pre>

<p>Also, th:if has an inverse attribute, th:unless, which we could have used in the previous example instead of using a not inside the OGNL expression:</p>

<p><a href="comments.html"
   th:href="@{/comments(prodId=${prod.id})}" 
   th:unless="${#lists.isEmpty(prod.comments)}">view</a></p>

<p>7.2 Switch statements</p>

<p>There is also a way to display content conditionally using the equivalent of a switch structure in Java: the th:switch / th:case attribute set.</p>

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
</div>

<p>Note that as soon as one th:case attribute is evaluated as true, every other th:case attribute in the same switch context is evaluated as false.</p>

<p>The default option is specified as th:case=&rdquo;*&rdquo;:</p>

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

<p>8 Template Layout
8.1 Including template fragments
Defining and referencing fragments</p>

<p>In our templates, we will often want to include parts from other templates, parts like footers, headers, menus…</p>

<p>In order to do this, Thymeleaf needs us to define these parts, “fragments”, for inclusion, which can be done using the th:fragment attribute.</p>

<p>Say we want to add a standard copyright footer to all our grocery pages, so we create a /WEB-INF/templates/footer.html file containing this code:</p>

<p>&lt;!DOCTYPE html&gt;</p>

<p><html xmlns:th="http://www.thymeleaf.org"></p>

<p><body></p>

<pre><code>&lt;div th:fragment=&quot;copy&quot;&gt;
  &amp;copy; 2011 The Good Thymes Virtual Grocery
&lt;/div&gt;
</code></pre>

<p></body></p>

<p></html></p>

<p>The code above defines a fragment called copy that we can easily include in our home page using one of the th:insert or th:replace attributes (and also th:include, though its use is no longer recommended since Thymeleaf 3.0):</p>

<p><body></p>

<p>&hellip;</p>

<p><div th:insert="~{footer :: copy}"></div></p>

<p></body></p>

<p>Note that th:insert expects a fragment expression (~{&hellip;}), which is an expression that results in a fragment. In the above example though, which is a non-complex fragment expression, the (~{,}) enclosing is completely optional, so the code above would be equivalent to:</p>

<p><body></p>

<p>&hellip;</p>

<p><div th:insert="footer :: copy"></div></p>

<p></body></p>

<p>Fragment specification syntax</p>

<p>The syntax of fragment expressions is quite straightforward. There are three different formats:</p>

<pre><code>&quot;~{templatename::selector}&quot; Includes the fragment resulting from applying the specified Markup Selector on the template named templatename. Note that selector can be a mere fragment name, so you could specify something as simple as ~{templatename::fragmentname} like in the ~{footer :: copy} above.

    Markup Selector syntax is defined by the underlying AttoParser parsing library, and is similar to XPath expressions or CSS selectors. See Appendix C for more info.

&quot;~{templatename}&quot; Includes the complete template named templatename.

    Note that the template name you use in th:insert/th:replace tags will have to be resolvable by the Template Resolver currently being used by the Template Engine.

~{::selector}&quot; or &quot;~{this::selector}&quot; Inserts a fragment from the same template, matching selector. If not found on the template where the expression appears, the stack of template calls (insertions) is traversed towards the originally processed template (the root), until selector matches at some level.
</code></pre>

<p>Both templatename and selector in the above examples can be fully-featured expressions (even conditionals!) like:</p>

<div th:insert="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>

<p>Note again how the surrounding ~{&hellip;} envelope is optional in th:insert/th:replace.</p>

<p>Fragments can include any th:* attributes. These attributes will be evaluated once the fragment is included into the target template (the one with the th:insert/th:replace attribute), and they will be able to reference any context variables defined in this target template.</p>

<pre><code>A big advantage of this approach to fragments is that you can write your fragments in pages that are perfectly displayable by a browser, with a complete and even valid markup structure, while still retaining the ability to make Thymeleaf include them into other templates.
</code></pre>

<p>Referencing fragments without th:fragment</p>

<p>Thanks to the power of Markup Selectors, we can include fragments that do not use any th:fragment attributes. It can even be markup code coming from a different application with no knowledge of Thymeleaf at all:</p>

<p>&hellip;
<div id="copy-section">
  &copy; 2011 The Good Thymes Virtual Grocery
</div>
&hellip;</p>

<p>We can use the fragment above simply referencing it by its id attribute, in a similar way to a CSS selector:</p>

<p><body></p>

<p>&hellip;</p>

<p><div th:insert="~{footer :: #copy-section}"></div></p>

<p></body></p>

<p>Difference between th:insert and th:replace (and th:include)</p>

<p>And what is the difference between th:insert and th:replace (and th:include, not recommended since 3.0)?</p>

<pre><code>th:insert is the simplest: it will simply insert the specified fragment as the body of its host tag.

th:replace actually replaces its host tag with the specified fragment.

th:include is similar to th:insert, but instead of inserting the fragment it only inserts the contents of this fragment.
</code></pre>

<p>So an HTML fragment like this:</p>

<footer th:fragment="copy">
  &copy; 2011 The Good Thymes Virtual Grocery
</footer>

<p>…included three times in host <div> tags, like this:</p>

<p><body></p>

<p>&hellip;</p>

<p><div th:insert="footer :: copy"></div></p>

<p><div th:replace="footer :: copy"></div></p>

<p><div th:include="footer :: copy"></div></p>

<p></body></p>

<p>…will result in:</p>

<p><body></p>

<p>&hellip;</p>

<p><div>
    <footer>
      &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
  </div></p>

<p><footer>
    &copy; 2011 The Good Thymes Virtual Grocery
  </footer></p>

<p><div>
    &copy; 2011 The Good Thymes Virtual Grocery
  </div></p>

<p></body></p>

<p>8.2 Parameterizable fragment signatures</p>

<p>In order to create a more function-like mechanism for template fragments, fragments defined with th:fragment can specify a set of parameters:</p>

<div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>

<p>This requires the use of one of these two syntaxes to call the fragment from th:insert or th:replace:</p>

<div th:replace="::frag (${value1},${value2})">...</div>
<div th:replace="::frag (onevar=${value1},twovar=${value2})">...</div>

<p>Note that order is not important in the last option:</p>

<div th:replace="::frag (twovar=${value2},onevar=${value1})">...</div>

<p>Fragment local variables without fragment arguments</p>

<p>Even if fragments are defined without arguments like this:</p>

<div th:fragment="frag">
    ...
</div>

<p>We could use the second syntax specified above to call them (and only the second one):</p>

<div th:replace="::frag (onevar=${value1},twovar=${value2})">

This would be equivalent to a combination of th:replace and th:with:

<div th:replace="::frag" th:with="onevar=${value1},twovar=${value2}">

Note that this specification of local variables for a fragment – no matter whether it has an argument signature or not – does not cause the context to be emptied prior to its execution. Fragments will still be able to access every context variable being used at the calling template like they currently are.
th:assert for in-template assertions

The th:assert attribute can specify a comma-separated list of expressions which should be evaluated and produce true for every evaluation, raising an exception if not.

<div th:assert="${onevar},(${twovar} != 43)">...</div>

<p>This comes in handy for validating parameters at a fragment signature:</p>

<header th:fragment="contentheader(title)" th:assert="${!#strings.isEmpty(title)}">...</header>

<p>8.3 Flexible layouts: beyond mere fragment insertion</p>

<p>Thanks to fragment expressions, we can specify parameters for fragments that are not texts, numbers, bean objects… but instead fragments of markup.</p>

<p>This allows us to create our fragments in a way such that they can be enriched with markup coming from the calling templates, resulting in a very flexible template layout mechanism.</p>

<p>Note the use of the title and links variables in the fragment below:</p>

<p><head th:fragment="common_header(title,links)"></p>

<p><title th:replace="${title}">The awesome application</title></p>

<p><!-- Common styles and scripts -->
  <link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}">
  <link rel="shortcut icon" th:href="@{/images/favicon.ico}">
  <script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script></p>

<p><!--/* Per-page placeholder for additional links */-->
  <th:block th:replace="${links}" /></p>

<p></head></p>

<p>We can now call this fragment like:</p>

<p>&hellip;
<head th:replace="base :: common_header(~{::title},~{::link})"></p>

<p><title>Awesome - Main</title></p>

<p><link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
  <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}"></p>

<p></head>
&hellip;</p>

<p>…and the result will use the actual <title> and <link> tags from our calling template as the values of the title and links variables, resulting in our fragment being customized during insertion:</p>

<p>&hellip;
<head></p>

<p><title>Awesome - Main</title></p>

<p><!-- Common styles and scripts -->
  <link rel="stylesheet" type="text/css" media="all" href="/awe/css/awesomeapp.css">
  <link rel="shortcut icon" href="/awe/images/favicon.ico">
  <script type="text/javascript" src="/awe/sh/scripts/codebase.js"></script></p>

<p><link rel="stylesheet" href="/awe/css/bootstrap.min.css">
  <link rel="stylesheet" href="/awe/themes/smoothness/jquery-ui.css"></p>

<p></head>
&hellip;</p>

<p>Using the empty fragment</p>

<p>A special fragment expression, the empty fragment (~{}), can be used for specifying no markup. Using the previous example:</p>

<p><head th:replace="base :: common_header(~{::title},~{})"></p>

<p><title>Awesome - Main</title></p>

<p></head>
&hellip;</p>

<p>Note how the second parameter of the fragment (links) is set to the empty fragment and therefore nothing is written for the <th:block th:replace="${links}" /> block:</p>

<p>&hellip;
<head></p>

<p><title>Awesome - Main</title></p>

<p><!-- Common styles and scripts -->
  <link rel="stylesheet" type="text/css" media="all" href="/awe/css/awesomeapp.css">
  <link rel="shortcut icon" href="/awe/images/favicon.ico">
  <script type="text/javascript" src="/awe/sh/scripts/codebase.js"></script></p>

<p></head>
&hellip;</p>

<p>Using the no-operation token</p>

<p>The no-op can be also used as a parameter to a fragment if we just want to let our fragment use its current markup as a default value. Again, using the common_header example:</p>

<p>&hellip;
<head th:replace="base :: common_header(_,~{::link})"></p>

<p><title>Awesome - Main</title></p>

<p><link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
  <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}"></p>

<p></head>
&hellip;</p>

<p>See how the title argument (first argument of the common<em>header fragment) is set to no-op (</em>), which results in this part of the fragment not being executed at all (title = no-operation):</p>

<p><title th:replace="${title}">The awesome application</title></p>

<p>So the result is:</p>

<p>&hellip;
<head></p>

<p><title>The awesome application</title></p>

<p><!-- Common styles and scripts -->
  <link rel="stylesheet" type="text/css" media="all" href="/awe/css/awesomeapp.css">
  <link rel="shortcut icon" href="/awe/images/favicon.ico">
  <script type="text/javascript" src="/awe/sh/scripts/codebase.js"></script></p>

<p><link rel="stylesheet" href="/awe/css/bootstrap.min.css">
  <link rel="stylesheet" href="/awe/themes/smoothness/jquery-ui.css"></p>

<p></head>
&hellip;</p>

<p>Advanced conditional insertion of fragments</p>

<p>The availability of both the emtpy fragment and no-operation token allows us to perform conditional insertion of fragments in a very easy and elegant way.</p>

<p>For example, we could do this in order to insert our common :: adminhead fragment only if the user is an administrator, and insert nothing (emtpy fragment) if not:</p>

<p>&hellip;
<div th:insert="${user.isAdmin()} ? ~{common :: adminhead} : ~{}">&hellip;</div>
&hellip;</p>

<p>Also, we can use the no-operation token in order to insert a fragment only if the specified condition is met, but leave the markup without modifications if the condition is not met:</p>

<p>&hellip;
<div th:insert="${user.isAdmin()} ? ~{common :: adminhead} : _">
    Welcome [[${user.name}]], click <a th:href="@{/support}">here</a> for help-desk support.
</div>
&hellip;</p>

<p>Additionally, if we have configured our template resolvers to check for existence of the template resources –- by means of their checkExistence flag -– we can use the existence of the fragment itself as the condition in a default operation:</p>

<p>&hellip;
<!-- The body of the <div> will be used if the "common :: salutation" fragment  -->
<!-- does not exist (or is empty).                                              -->
<div th:insert="~{common :: salutation} ?: _">
    Welcome [[${user.name}]], click <a th:href="@{/support}">here</a> for help-desk support.
</div>
&hellip;</p>

<p>8.4 Removing template fragments</p>

<p>Back to the example application, let’s revisit the last version of our product list template:</p>

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    <td>
      <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
      <a href="comments.html" 
         th:href="@{/product/comments(prodId=${prod.id})}" 
         th:unless="${#lists.isEmpty(prod.comments)}">view</a>
    </td>
  </tr>
</table>

<p>This code is just fine as a template, but as a static page (when directly open by a browser without Thymeleaf processing it) it would not make a nice prototype.</p>

<p>Why? Because, although perfectly displayable by browsers, that table only has a row, and this row has mock data. As a prototype, it simply wouldn’t look realistic enough… we should have more than one product, we need more rows.</p>

<p>So let’s add some:</p>

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    <td>
      <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
      <a href="comments.html" 
         th:href="@{/product/comments(prodId=${prod.id})}" 
         th:unless="${#lists.isEmpty(prod.comments)}">view</a>
    </td>
  </tr>
  <tr class="odd">
    <td>Blue Lettuce</td>
    <td>9.55</td>
    <td>no</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr>
    <td>Mild Cinnamon</td>
    <td>1.99</td>
    <td>yes</td>
    <td>
      <span>3</span> comment/s
      <a href="comments.html">view</a>
    </td>
  </tr>
</table>

<p>Ok, now we have three, definitely better for a prototype. But… what will happen when we process it with Thymeleaf?:</p>

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr>
    <td>Fresh Sweet Basil</td>
    <td>4.99</td>
    <td>yes</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr class="odd">
    <td>Italian Tomato</td>
    <td>1.25</td>
    <td>no</td>
    <td>
      <span>2</span> comment/s
      <a href="/gtvg/product/comments?prodId=2">view</a>
    </td>
  </tr>
  <tr>
    <td>Yellow Bell Pepper</td>
    <td>2.50</td>
    <td>yes</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr class="odd">
    <td>Old Cheddar</td>
    <td>18.75</td>
    <td>yes</td>
    <td>
      <span>1</span> comment/s
      <a href="/gtvg/product/comments?prodId=4">view</a>
    </td>
  </tr>
  <tr class="odd">
    <td>Blue Lettuce</td>
    <td>9.55</td>
    <td>no</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr>
    <td>Mild Cinnamon</td>
    <td>1.99</td>
    <td>yes</td>
    <td>
      <span>3</span> comment/s
      <a href="comments.html">view</a>
    </td>
  </tr>
</table>

<p>The last two rows are mock rows! Well, of course they are: iteration was only applied to the first row, so there is no reason why Thymeleaf should have removed the other two.</p>

<p>We need a way to remove those two rows during template processing. Let’s use the th:remove attribute on the second and third <tr> tags:</p>

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    <td>
      <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
      <a href="comments.html" 
         th:href="@{/product/comments(prodId=${prod.id})}" 
         th:unless="${#lists.isEmpty(prod.comments)}">view</a>
    </td>
  </tr>
  <tr class="odd" th:remove="all">
    <td>Blue Lettuce</td>
    <td>9.55</td>
    <td>no</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr th:remove="all">
    <td>Mild Cinnamon</td>
    <td>1.99</td>
    <td>yes</td>
    <td>
      <span>3</span> comment/s
      <a href="comments.html">view</a>
    </td>
  </tr>
</table>

<p>Once processed, everything will look again as it should:</p>

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr>
    <td>Fresh Sweet Basil</td>
    <td>4.99</td>
    <td>yes</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr class="odd">
    <td>Italian Tomato</td>
    <td>1.25</td>
    <td>no</td>
    <td>
      <span>2</span> comment/s
      <a href="/gtvg/product/comments?prodId=2">view</a>
    </td>
  </tr>
  <tr>
    <td>Yellow Bell Pepper</td>
    <td>2.50</td>
    <td>yes</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr class="odd">
    <td>Old Cheddar</td>
    <td>18.75</td>
    <td>yes</td>
    <td>
      <span>1</span> comment/s
      <a href="/gtvg/product/comments?prodId=4">view</a>
    </td>
  </tr>
</table>

<p>And what does that all value in the attribute, mean? th:remove can behave in five different ways, depending on its value:</p>

<pre><code>all: Remove both the containing tag and all its children.
body: Do not remove the containing tag, but remove all its children.
tag: Remove the containing tag, but do not remove its children.
all-but-first: Remove all children of the containing tag except the first one.
none : Do nothing. This value is useful for dynamic evaluation.
</code></pre>

<p>What can that all-but-first value be useful for? It will let us save some th:remove=&ldquo;all&rdquo; when prototyping:</p>

<table>
  <thead>
    <tr>
      <th>NAME</th>
      <th>PRICE</th>
      <th>IN STOCK</th>
      <th>COMMENTS</th>
    </tr>
  </thead>
  <tbody th:remove="all-but-first">
    <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
      <td th:text="${prod.name}">Onions</td>
      <td th:text="${prod.price}">2.41</td>
      <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
      <td>
        <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
        <a href="comments.html" 
           th:href="@{/product/comments(prodId=${prod.id})}" 
           th:unless="${#lists.isEmpty(prod.comments)}">view</a>
      </td>
    </tr>
    <tr class="odd">
      <td>Blue Lettuce</td>
      <td>9.55</td>
      <td>no</td>
      <td>
        <span>0</span> comment/s
      </td>
    </tr>
    <tr>
      <td>Mild Cinnamon</td>
      <td>1.99</td>
      <td>yes</td>
      <td>
        <span>3</span> comment/s
        <a href="comments.html">view</a>
      </td>
    </tr>
  </tbody>
</table>

<p>The th:remove attribute can take any Thymeleaf Standard Expression, as long as it returns one of the allowed String values (all, tag, body, all-but-first or none).</p>

<p>This means removals could be conditional, like:</p>

<p><a href="/something" th:remove="${condition}? tag : none">Link text not to be removed</a></p>

<p>Also note that th:remove considers null a synonym to none, so the following works the same as the example above:</p>

<p><a href="/something" th:remove="${condition}? tag">Link text not to be removed</a></p>

<p>In this case, if ${condition} is false, null will be returned, and thus no removal will be performed.
8.5 Layout Inheritance</p>

<p>To be able to have a single file as layout, fragments can be used. An example of a simple layout having title and content using th:fragment and th:replace:</p>

<p>&lt;!DOCTYPE html&gt;
<html th:fragment="layout (title, content)" xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:replace="${title}">Layout Title</title>
</head>
<body>
    <h1>Layout H1</h1>
    <div th:replace="${content}">
        <p>Layout content</p>
    </div>
    <footer>
        Layout footer
    </footer>
</body>
</html></p>

<p>This example declares a fragment called layout having title and content as parameters. Both will be replaced on page inheriting it by provided fragment expressions in the example below.</p>

<p>&lt;!DOCTYPE html&gt;
<html th:replace="~{layoutFile :: layout(~{::title}, ~{::section})}">
<head>
    <title>Page Title</title>
</head>
<body>
<section>
    <p>Page content</p>
    <div>Included on page</div>
</section>
</body>
</html></p>

<p>In this file, the html tag will be replaced by layout, but in the layout title and content will have been replaced by title and section blocks respectively.</p>

<p>If desired, the layout can be composed by several fragments as header and footer.
9 Local Variables</p>

<p>Thymeleaf calls local variables the variables that are defined for a specific fragment of a template, and are only available for evaluation inside that fragment.</p>

<p>An example we have already seen is the prod iter variable in our product list page:</p>

<p><tr th:each="prod : ${prods}">
    &hellip;
</tr></p>

<p>That prod variable will be available only within the bounds of the <tr> tag. Specifically:</p>

<pre><code>It will be available for any other th:* attributes executing in that tag with less precedence than th:each (which means they will execute after th:each).
It will be available for any child element of the &lt;tr&gt; tag, such as any &lt;td&gt; elements.
</code></pre>

<p>Thymeleaf offers you a way to declare local variables without iteration, using the th:with attribute, and its syntax is like that of attribute value assignments:</p>

<div th:with="firstPer=${persons[0]}">
  <p>
    The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
  </p>
</div>

<p>When th:with is processed, that firstPer variable is created as a local variable and added to the variables map coming from the context, so that it is available for evaluation along with any other variables declared in the context, but only within the bounds of the containing <div> tag.</p>

<p>You can define several variables at the same time using the usual multiple assignment syntax:</p>

<div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
  <p>
    The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
  </p>
  <p>
    But the name of the second person is 
    <span th:text="${secondPer.name}">Marcus Antonius</span>.
  </p>
</div>

<p>The th:with attribute allows reusing variables defined in the same attribute:</p>

<div th:with="company=${user.company + ' Co.'},account=${accounts[company]}">...</div>

<p>Let’s use this in our Grocery’s home page! Remember the code we wrote for outputting a formatted date?</p>

<p>
  Today is: 
  <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 february 2011</span>
</p>

<p>Well, what if we wanted that &ldquo;dd MMMM yyyy&rdquo; to actually depend on the locale? For example, we might want to add the following message to our home_en.properties:</p>

<p>date.format=MMMM dd&rdquo;,&rdquo; yyyy</p>

<p>…and an equivalent one to our home_es.properties:</p>

<p>date.format=dd &ldquo;de&rdquo; MMMM&rdquo;,&rdquo; yyyy</p>

<p>Now, let’s use th:with to get the localized date format into a variable, and then use it in our th:text expression:</p>

<p th:with="df=#{date.format}">
  Today is: <span th:text="${#calendars.format(today,df)}">13 February 2011</span>
</p>

<p>That was clean and easy. In fact, given the fact that th:with has a higher precedence than th:text, we could have solved this all in the span tag:</p>

<p>
  Today is: 
  <span th:with="df=#{date.format}" 
        th:text="${#calendars.format(today,df)}">13 February 2011</span>
</p>

<p>You might be thinking: Precedence? We haven’t talked about that yet! Well, don’t worry because that is exactly what the next chapter is about.
10 Attribute Precedence</p>

<p>What happens when you write more than one th:* attribute in the same tag? For example:</p>

<ul>
  <li th:each="item : ${items}" th:text="${item.description}">Item description here...</li>
</ul>

<p>We would expect that th:each attribute to execute before the th:text so that we get the results we want, but given the fact that the HTML/XML standards do not give any kind of meaning to the order in which the attributes in a tag are written, a precedence mechanism had to be established in the attributes themselves in order to be sure that this will work as expected.</p>

<p>So, all Thymeleaf attributes define a numeric precedence, which establishes the order in which they are executed in the tag. This order is:
Order   Feature     Attributes
1   Fragment inclusion  th:insert
th:replace
2   Fragment iteration  th:each
3   Conditional evaluation  th:if
th:unless
th:switch
th:case
4   Local variable definition   th:object
th:with
5   General attribute modification  th:attr
th:attrprepend
th:attrappend
6   Specific attribute modification     th:value
th:href
th:src
&hellip;
7   Text (tag body modification)    th:text
th:utext
8   Fragment specification  th:fragment
9   Fragment removal    th:remove</p>

<p>This precedence mechanism means that the above iteration fragment will give exactly the same results if the attribute position is inverted (although it would be slightly less readable):</p>

<ul>
  <li th:text="${item.description}" th:each="item : ${items}">Item description here...</li>
</ul>

<p>11 Comments and Blocks
11.1. Standard HTML/XML comments</p>

<p>Standard HTML/XML comments <!-- ... --> can be used anywhere in Thymeleaf templates. Anything inside these comments won’t be processed by Thymeleaf, and will be copied verbatim to the result:</p>

<!-- User info follows -->

<div th:text="${...}">
  ...
</div>

<p>11.2. Thymeleaf parser-level comment blocks</p>

<p>Parser-level comment blocks are code that will be simply removed from the template when Thymeleaf parses it. They look like this:</p>

<!--/* This code will be removed at Thymeleaf parsing time! */-->

<p>Thymeleaf will remove everything between <!--/* and */-->, so these comment blocks can also be used for displaying code when a template is statically open, knowing that it will be removed when Thymeleaf processes it:</p>

<!--/*--> 

<p><div>
     you can see me only before Thymeleaf processes me!
  </div>
<!--*/--></p>

<p>This might come very handy for prototyping tables with a lot of <tr>’s, for example:</p>

<table>
   <tr th:each="x : ${xs}">
     ...
   </tr>
   <!--/*-->
   <tr>
     ...
   </tr>
   <tr>
     ...
   </tr>
   <!--*/-->
</table>

<p>11.3. Thymeleaf prototype-only comment blocks</p>

<p>Thymeleaf allows the definition of special comment blocks marked to be comments when the template is open statically (i.e. as a prototype), but considered normal markup by Thymeleaf when executing the template.</p>

<p><span>hello!</span>
<!--/*/
  <div th:text="${...}">
    ...
  </div>
/*/-->
<span>goodbye!</span></p>

<p>Thymeleaf’s parsing system will simply remove the <!--/*/ and /*/--> markers, but not its contents, which will be left therefore uncommented. So when executing the template, Thymeleaf will actually see this:</p>

<p><span>hello!</span></p>

<p><div th:text="${...}">
    &hellip;
  </div></p>

<p><span>goodbye!</span></p>

<p>As with parser-level comment blocks, this feature is dialect-independent.
11.4. Synthetic th:block tag</p>

<p>Thymeleaf’s only element processor (not an attribute) included in the Standard Dialects is th:block.</p>

<p>th:block is a mere attribute container that allows template developers to specify whichever attributes they want. Thymeleaf will execute these attributes and then simply make the block, but not its contents, disappear.</p>

<p>So it could be useful, for example, when creating iterated tables that require more than one <tr> for each element:</p>

<table>
  <th:block th:each="user : ${users}">
    <tr>
        <td th:text="${user.login}">...</td>
        <td th:text="${user.name}">...</td>
    </tr>
    <tr>
        <td colspan="2" th:text="${user.address}">...</td>
    </tr>
  </th:block>
</table>

<p>And especially useful when used in combination with prototype-only comment blocks:</p>

<table>
    <!--/*/ <th:block th:each="user : ${users}"> /*/-->
    <tr>
        <td th:text="${user.login}">...</td>
        <td th:text="${user.name}">...</td>
    </tr>
    <tr>
        <td colspan="2" th:text="${user.address}">...</td>
    </tr>
    <!--/*/ </th:block> /*/-->
</table>

<p>Note how this solution allows templates to be valid HTML (no need to add forbidden <div> blocks inside <table>), and still works OK when open statically in browsers as prototypes!
12 Inlining
12.1 Expression inlining</p>

<p>Although the Standard Dialect allows us to do almost everything using tag attributes, there are situations in which we could prefer writing expressions directly into our HTML texts. For example, we could prefer writing this:</p>

<p>Hello, [[${session.user.name}]]!</p>

<p>…instead of this:</p>

<p>Hello, <span th:text="${session.user.name}">Sebastian</span>!</p>

<p>Expressions between [[&hellip;]] or [(&hellip;)] are considered inlined expressions in Thymeleaf, and inside them we can use any kind of expression that would also be valid in a th:text or th:utext attribute.</p>

<p>Note that, while [[&hellip;]] corresponds to th:text (i.e. result will be HTML-escaped), [(&hellip;)] corresponds to th:utext and will not perform any HTML-escaping. So with a variable such as msg = &lsquo;This is <b>great!</b>&rsquo;, given this fragment:</p>

<p>The message is "[(${msg})]"</p>

<p>The result will have those <b> tags unescaped, so:</p>

<p>The message is "This is <b>great!</b>"</p>

<p>Whereas if escaped like:</p>

<p>The message is "[[${msg}]]"</p>

<p>The result will be HTML-escaped:</p>

<p>The message is "This is &lt;b&gt;great!&lt;/b&gt;"</p>

<p>Note that text inlining is active by default in the body of every tag in our markup –- not the tags themselves -–, so there is nothing we need to do to enable it.
Inlining vs natural templates</p>

<p>If you come from other template engines in which this way of outputting text is the norm, you might be asking: Why aren’t we doing this from the beginning? It’s less code than all those th:text attributes!</p>

<p>Well, be careful there, because although you might find inlining quite interesting, you should always remember that inlined expressions will be displayed verbatim in your HTML files when you open them statically, so you probably won’t be able to use them as design prototypes anymore!</p>

<p>The difference between how a browser would statically display our fragment of code without using inlining…</p>

<p>Hello, Sebastian!</p>

<p>…and using it…</p>

<p>Hello, [[${session.user.name}]]!</p>

<p>…is quite clear in terms of design usefulness.
Disabling inlining</p>

<p>This mechanism can be disabled though, because there might actually be occasions in which we do want to output the [[&hellip;]] or [(&hellip;)] sequences without its contents being processed as an expression. For that, we will use th:inline=&ldquo;none&rdquo;:</p>

<p th:inline="none">A double array looks like this: [[1, 2, 3], [4, 5]]!</p>

<p>This will result in:</p>

<p>A double array looks like this: [[1, 2, 3], [4, 5]]!</p>

<p>12.2 Text inlining</p>

<p>Text inlining is very similar to the expression inlining capability we have just seen, but it actually adds more power. It has to be enabled explicitly with th:inline=&ldquo;text&rdquo;.</p>

<p>Text inlining not only allows us to use the same inlined expressions we just saw, but in fact processes tag bodies as if they were templates processed in the TEXT template mode, which allows us to perform text-based template logic (not only output expressions).</p>

<p>We will see more about this in the next chapter about the textual template modes.
12.3 JavaScript inlining</p>

<p>JavaScript inlining allows for a better integration of JavaScript <script> blocks in templates being processed in the HTML template mode.</p>

<p>As with text inlining, this is actually equivalent to processing the scripts contents as if they were templates in the JAVASCRIPT template mode, and therefore all the power of the textual template modes (see next chapter) will be at hand. However, in this section we will focus on how we can use it for adding the output of our Thymeleaf expressions into our JavaScript blocks.</p>

<p>This mode has to be explicitly enabled using th:inline=&ldquo;javascript&rdquo;:</p>

<script th:inline="javascript">
    ...
    var username = [[${session.user.name}]];
    ...
</script>

<p>This will result in:</p>

<script th:inline="javascript">
    ...
    var username = "Sebastian \"Fruity\" Applejuice";
    ...
</script>

<p>Two important things to note in the code above:</p>

<p>First, that JavaScript inlining will not only output the required text, but also enclose it with quotes and JavaScript-escape its contents, so that the expression results are output as a well-formed JavaScript literal.</p>

<p>Second, that this is happening because we are outputting the ${session.user.name} expression as escaped, i.e. using a double-bracket expression: [[${session.user.name}]]. If instead we used unescaped like:</p>

<script th:inline="javascript">
    ...
    var username = [(${session.user.name})];
    ...
</script>

<p>The result would look like:</p>

<script th:inline="javascript">
    ...
    var username = Sebastian "Fruity" Applejuice;
    ...
</script>

<p>…which is malformed JavaScript code. But outputting something unescaped might be what we need if we are building parts of our script by means of appending inlined expressions, so it’s good to have this tool at hand.
JavaScript natural templates</p>

<p>The mentioned intelligence of the JavaScript inlining mechanism goes much further than just applying JavaScript-specific escaping and outputting expression results as valid literals.</p>

<p>For example, we can wrap our (escaped) inlined expressions in JavaScript comments like:</p>

<script th:inline="javascript">
    ...
    var username = /*[[${session.user.name}]]*/ "Gertrud Kiwifruit";
    ...
</script>

<p>And Thymeleaf will ignore everything we have written after the comment and before the semicolon (in this case &lsquo;Gertrud Kiwifruit&rsquo;), so the result of executing this will look exactly like when we were not using the wrapping comments:</p>

<script th:inline="javascript">
    ...
    var username = "Sebastian \"Fruity\" Applejuice";
    ...
</script>

<p>But have another careful look at the original template code:</p>

<script th:inline="javascript">
    ...
    var username = /*[[${session.user.name}]]*/ "Gertrud Kiwifruit";
    ...
</script>

<p>Note how this is valid JavaScript code. And it will perfectly execute when you open your template file in a static manner (without executing it at a server).</p>

<p>So what we have here is a way to do JavaScript natural templates!
Advanced inlined evaluation and JavaScript serialization</p>

<p>An important thing to note regarding JavaScript inlining is that this expression evaluation is intelligent and not limited to Strings. Thymeleaf will correctly write in JavaScript syntax the following kinds of objects:</p>

<pre><code>Strings
Numbers
Booleans
Arrays
Collections
Maps
Beans (objects with getter and setter methods)
</code></pre>

<p>For example, if we had the following code:</p>

<script th:inline="javascript">
    ...
    var user = /*[[${session.user}]]*/ null;
    ...
</script>

<p>That ${session.user} expression will evaluate to a User object, and Thymeleaf will correctly convert it to Javascript syntax:</p>

<script th:inline="javascript">
    ...
    var user = {"age":null,"firstName":"John","lastName":"Apricot",
                "name":"John Apricot","nationality":"Antarctica"};
    ...
</script>

<p>The way this JavaScript serialization is done is by means of an implementation of the org.thymeleaf.standard.serializer.IStandardJavaScriptSerializer interface, which can be configured at the instance of the StandardDialect being used at the template engine.</p>

<p>The default implementation of this JS serialization mechanism will look for the Jackson library in the classpath and, if present, will use it. If not, it will apply a built-in serialization mechanism that covers the needs of most scenarios and produces similar results (but is less flexible).
12.4 CSS inlining</p>

<p>Thymeleaf also allows the use of inlining in CSS <style> tags, such as:</p>

<style th:inline="css">
  ...
</style>

<p>For example, say we have two variables set to two different String values:</p>

<p>classname = &lsquo;main elems&rsquo;
align = &lsquo;center&rsquo;</p>

<p>We could use them just like:</p>

<style th:inline="css">
    .[[${classname}]] {
      text-align: [[${align}]];
    }
</style>

<p>And the result would be:</p>

<style th:inline="css">
    .main\ elems {
      text-align: center;
    }
</style>

<p>Note how CSS inlining also bears some intelligence, just like JavaScript’s. Specifically, expressions output via escaped expressions like [[${classname}]] will be escaped as CSS identifiers. That is why our classname = &lsquo;main elems&rsquo; has turned into main\ elems in the fragment of code above.
Advanced features: CSS natural templates, etc.</p>

<p>In an equivalent way to what was explained before for JavaScript, CSS inlining also allows for our <style> tags to work both statically and dynamically, i.e. as CSS natural templates by means of wrapping inlined expressions in comments. See:</p>

<style th:inline="css">
    .main\ elems {
      text-align: /*[[${align}]]*/ left;
    }
</style>

<p>13 Textual template modes
13.1 Textual syntax</p>

<p>Three of the Thymeleaf template modes are considered textual: TEXT, JAVASCRIPT and CSS. This differentiates them from the markup template modes: HTML and XML.</p>

<p>The key difference between textual template modes and the markup ones is that in a textual template there are no tags into which to insert logic in the form of attributes, so we have to rely on other mechanisms.</p>

<p>The first and most basic of these mechanisms is inlining, which we have already detailed in the previous chapter. Inlining syntax is the most simple way to output results of expressions in textual template mode, so this is a perfectly valid template for a text email.</p>

<p>Dear [(${name})],</p>

<p>Please find attached the results of the report you requested
  with name &ldquo;[(${report.name})]&ldquo;.</p>

<p>Sincerely,
    The Reporter.</p>

<p>Even without tags, the example above is a complete and valid Thymeleaf template that can be executed in the TEXT template mode.</p>

<p>But in order to include more complex logic than mere output expressions, we need a new non-tag-based syntax:</p>

<p>[# th:each=&ldquo;item : ${items}&ldquo;]
  - [(${item})]
[/]</p>

<p>Which is actually the condensed version of the more verbose:</p>

<p>[#th:block th:each=&ldquo;item : ${items}&ldquo;]
  - [#th:block th:utext=&ldquo;${item}&rdquo; /]
[/th:block]</p>

<p>Note how this new syntax is based on elements (i.e. processable tags) that are declared as [#element &hellip;] instead of <element ...>. Elements are open like [#element &hellip;] and closed like [/element], and standalone tags can be declared by minimizing the open element with a / in a way almost equivalent to XML tags: [#element &hellip; /].</p>

<p>The Standard Dialect only contains a processor for one of these elements: the already-known th:block, though we could extend this in our dialects and create new elements in the usual way. Also, the th:block element ([#th:block &hellip;] &hellip; [/th:block]) is allowed to be abbreviated as the empty string ([# &hellip;] &hellip; [/]), so the above block is actually equivalent to:</p>

<p>[# th:each=&ldquo;item : ${items}&ldquo;]
  - [# th:utext=&ldquo;${item}&rdquo; /]
[/]</p>

<p>And given [# th:utext=&ldquo;${item}&rdquo; /] is equivalent to an inlined unescaped expression, we could just use it in order to have less code. Thus we end up with the first fragment of code we saw above:</p>

<p>[# th:each=&ldquo;item : ${items}&ldquo;]
  - [(${item})]
[/]</p>

<p>Note that the textual syntax requires full element balance (no unclosed tags) and quoted attributes – it’s more XML-style than HTML-style.</p>

<p>Let’s have a look at a more complete example of a TEXT template, a plain text email template:</p>

<p>Dear [(${customer.name})],</p>

<p>This is the list of our products:</p>

<p>[# th:each=&ldquo;prod : ${products}&ldquo;]
   - [(${prod.name})]. Price: [(${prod.price})] EUR/kg
[/]</p>

<p>Thanks,
  The Thymeleaf Shop</p>

<p>After executing, the result of this could be something like:</p>

<p>Dear Mary Ann Blueberry,</p>

<p>This is the list of our products:</p>

<ul>
<li>Apricots. Price: 1.12 EUR/kg</li>
<li>Bananas. Price: 1.78 EUR/kg</li>
<li>Apples. Price: 0.85 EUR/kg</li>
<li>Watermelon. Price: 1.91 EUR/kg</li>
</ul>

<p>Thanks,
  The Thymeleaf Shop</p>

<p>And another example in JAVASCRIPT template mode, a greeter.js file, we process as a textual template and which result we call from our HTML pages. Note this is not a <script> block in an HTML template, but a .js file being processed as a template on its own:</p>

<p>var greeter = function() {</p>

<pre><code>var username = [[${session.user.name}]];

[# th:each=&quot;salut : ${salutations}&quot;]    
  alert([[${salut}]] + &quot; &quot; + username);
[/]
</code></pre>

<p>};</p>

<p>After executing, the result of this could be something like:</p>

<p>var greeter = function() {</p>

<pre><code>var username = &quot;Bertrand \&quot;Crunchy\&quot; Pear&quot;;

  alert(&quot;Hello&quot; + &quot; &quot; + username);
  alert(&quot;Ol\u00E1&quot; + &quot; &quot; + username);
  alert(&quot;Hola&quot; + &quot; &quot; + username);
</code></pre>

<p>};</p>

<p>Escaped element attributes</p>

<p>In order to avoid interactions with parts of the template that might be processed in other modes (e.g. text-mode inlining inside an HTML template), Thymeleaf 3.0 allows the attributes in elements in its textual syntax to be escaped. So:</p>

<pre><code>Attributes in TEXT template mode will be HTML-unescaped.
Attributes in JAVASCRIPT template mode will be JavaScript-unescaped.
Attributes in CSS template mode will be CSS-unescaped.
</code></pre>

<p>So this would be perfectly OK in a TEXT-mode template (note the &gt;):</p>

<p>[# th:if=&ldquo;${120&lt;user.age}&ldquo;]
     Congratulations!
  [/]</p>

<p>Of course that &lt; would make no sense in a real text template, but it is a good idea if we are processing an HTML template with a th:inline=&ldquo;text&rdquo; block containing the code above and we want to make sure our browser doesn’t take that &lt;user.age for the name of an open tag when statically opening the file as a prototype.
13.2 Extensibility</p>

<p>One of the advantages of this syntax is that it is just as extensible as the markup one. Developers can still define their own dialects with custom elements and attributes, apply a prefix to them (optionally), and then use them in textual template modes:</p>

<p>[#myorg:dosomething myorg:importantattr=&ldquo;211&rdquo;]some text[/myorg:dosomething]</p>

<p>13.3 Textual prototype-only comment blocks: adding code</p>

<p>The JAVASCRIPT and CSS template modes (not available for TEXT) allow including code between a special comment syntax /<em>[+&hellip;+]</em>/ so that Thymeleaf will automatically uncomment such code when processing the template:</p>

<p>var x = 23;</p>

<p>/*[+</p>

<p>var msg  = &ldquo;This is a working application&rdquo;;</p>

<p>+]*/</p>

<p>var f = function() {
    &hellip;</p>

<p>Will be executed as:</p>

<p>var x = 23;</p>

<p>var msg  = &ldquo;This is a working application&rdquo;;</p>

<p>var f = function() {
&hellip;</p>

<p>You can include expressions inside these comments, and they will be evaluated:</p>

<p>var x = 23;</p>

<p>/*[+</p>

<p>var msg  = &ldquo;Hello, &rdquo; + [[${session.user.name}]];</p>

<p>+]*/</p>

<p>var f = function() {
&hellip;</p>

<p>13.4 Textual parser-level comment blocks: removing code</p>

<p>In a way similar to that of prototype-only comment blocks, all the three textual template modes (TEXT, JAVASCRIPT and CSS) make it possible to instruct Thymeleaf to remove code between special /*[- <em>/ and /</em> -]*/ marks, like this:</p>

<p>var x = 23;</p>

<p>/*[- */</p>

<p>var msg  = &ldquo;This is shown only when executed statically!&rdquo;;</p>

<p>/* -]*/</p>

<p>var f = function() {
&hellip;</p>

<p>Or this, in TEXT mode:</p>

<p>&hellip;
/<em>[- Note the user is obtained from the session, which must exist -]</em>/
Welcome [(${session.user.name})]!
&hellip;</p>

<p>13.5 Natural JavaScript and CSS templates</p>

<p>As seen in the previous chapter, JavaScript and CSS inlining offer the possibility to include inlined expressions inside JavaScript/CSS comments, like:</p>

<p>&hellip;
var username = /<em>[[${session.user.name}]]</em>/ &ldquo;Sebastian Lychee&rdquo;;
&hellip;</p>

<p>…which is valid JavaScript, and once executed could look like:</p>

<p>&hellip;
var username = &ldquo;John Apricot&rdquo;;
&hellip;</p>

<p>This same trick of enclosing inlined expressions inside comments can in fact be used for the entire textual mode syntax:</p>

<p>/<em>[# th:if=&ldquo;${user.admin}&rdquo;]</em>/
     alert(&lsquo;Welcome admin&rsquo;);
  /<em>[/]</em>/</p>

<p>That alert in the code above will be shown when the template is open statically – because it is 100% valid JavaScript –, and also when the template is run if the user is an admin. It is equivalent to:</p>

<p>[# th:if=&ldquo;${user.admin}&rdquo;]
     alert(&lsquo;Welcome admin&rsquo;);
  [/]</p>

<p>…which is actually the code to which the initial version is converted during template parsing.</p>

<p>Note however that wrapping elements in comments does not clean the lines they live in (to the right until a ; is found) as inlined output expressions do. That behaviour is reserved for inlined output expressions only.</p>

<p>So Thymeleaf 3.0 allows the development of complex JavaScript scripts and CSS style sheets in the form of natural templates, valid both as a prototype and as a working template.
14 Some more pages for our grocery</p>

<p>Now we know a lot about using Thymeleaf, we can add some new pages to our website for order management.</p>

<p>Note that we will focus on HTML code, but you can have a look at the bundled source code if you want to see the corresponding controllers.
14.1 Order List</p>

<p>Let’s start by creating an order list page, /WEB-INF/templates/order/list.html:</p>

<p>&lt;!DOCTYPE html&gt;</p>

<p><html xmlns:th="http://www.thymeleaf.org"></p>

<p><head></p>

<pre><code>&lt;title&gt;Good Thymes Virtual Grocery&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; media=&quot;all&quot; 
      href=&quot;../../../css/gtvg.css&quot; th:href=&quot;@{/css/gtvg.css}&quot; /&gt;
</code></pre>

<p></head></p>

<p><body></p>

<pre><code>&lt;h1&gt;Order list&lt;/h1&gt;

&lt;table&gt;
  &lt;tr&gt;
    &lt;th&gt;DATE&lt;/th&gt;
    &lt;th&gt;CUSTOMER&lt;/th&gt;
    &lt;th&gt;TOTAL&lt;/th&gt;
    &lt;th&gt;&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr th:each=&quot;o : ${orders}&quot; th:class=&quot;${oStat.odd}? 'odd'&quot;&gt;
    &lt;td th:text=&quot;${#calendars.format(o.date,'dd/MMM/yyyy')}&quot;&gt;13 jan 2011&lt;/td&gt;
    &lt;td th:text=&quot;${o.customer.name}&quot;&gt;Frederic Tomato&lt;/td&gt;
    &lt;td th:text=&quot;${#aggregates.sum(o.orderLines.{purchasePrice * amount})}&quot;&gt;23.32&lt;/td&gt;
    &lt;td&gt;
      &lt;a href=&quot;details.html&quot; th:href=&quot;@{/order/details(orderId=${o.id})}&quot;&gt;view&lt;/a&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;
  &lt;a href=&quot;../home.html&quot; th:href=&quot;@{/}&quot;&gt;Return to home&lt;/a&gt;
&lt;/p&gt;
</code></pre>

<p></body></p>

<p></html></p>

<p>There’s nothing here that should surprise us, except for this little bit of OGNL magic:</p>

<p><td th:text="${#aggregates.sum(o.orderLines.{purchasePrice * amount})}">23.32</td></p>

<p>What that does is, for each order line (OrderLine object) in the order, multiply its purchasePrice and amount properties (by calling the corresponding getPurchasePrice() and getAmount() methods) and return the result into a list of numbers, later aggregated by the #aggregates.sum(&hellip;) function in order to obtain the order total price.</p>

<p>You’ve got to love the power of OGNL.
14.2 Order Details</p>

<p>Now for the order details page, in which we will make a heavy use of asterisk syntax:</p>

<p>&lt;!DOCTYPE html&gt;</p>

<p><html xmlns:th="http://www.thymeleaf.org"></p>

<p><head>
    <title>Good Thymes Virtual Grocery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all" 
          href="../../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  </head></p>

<p><body th:object="${order}"></p>

<pre><code>&lt;h1&gt;Order details&lt;/h1&gt;

&lt;div&gt;
  &lt;p&gt;&lt;b&gt;Code:&lt;/b&gt; &lt;span th:text=&quot;*{id}&quot;&gt;99&lt;/span&gt;&lt;/p&gt;
  &lt;p&gt;
    &lt;b&gt;Date:&lt;/b&gt;
    &lt;span th:text=&quot;*{#calendars.format(date,'dd MMM yyyy')}&quot;&gt;13 jan 2011&lt;/span&gt;
  &lt;/p&gt;
&lt;/div&gt;

&lt;h2&gt;Customer&lt;/h2&gt;

&lt;div th:object=&quot;*{customer}&quot;&gt;
  &lt;p&gt;&lt;b&gt;Name:&lt;/b&gt; &lt;span th:text=&quot;*{name}&quot;&gt;Frederic Tomato&lt;/span&gt;&lt;/p&gt;
  &lt;p&gt;
    &lt;b&gt;Since:&lt;/b&gt;
    &lt;span th:text=&quot;*{#calendars.format(customerSince,'dd MMM yyyy')}&quot;&gt;1 jan 2011&lt;/span&gt;
  &lt;/p&gt;
&lt;/div&gt;

&lt;h2&gt;Products&lt;/h2&gt;

&lt;table&gt;
  &lt;tr&gt;
    &lt;th&gt;PRODUCT&lt;/th&gt;
    &lt;th&gt;AMOUNT&lt;/th&gt;
    &lt;th&gt;PURCHASE PRICE&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr th:each=&quot;ol,row : *{orderLines}&quot; th:class=&quot;${row.odd}? 'odd'&quot;&gt;
    &lt;td th:text=&quot;${ol.product.name}&quot;&gt;Strawberries&lt;/td&gt;
    &lt;td th:text=&quot;${ol.amount}&quot; class=&quot;number&quot;&gt;3&lt;/td&gt;
    &lt;td th:text=&quot;${ol.purchasePrice}&quot; class=&quot;number&quot;&gt;23.32&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;

&lt;div&gt;
  &lt;b&gt;TOTAL:&lt;/b&gt;
  &lt;span th:text=&quot;*{#aggregates.sum(orderLines.{purchasePrice * amount})}&quot;&gt;35.23&lt;/span&gt;
&lt;/div&gt;

&lt;p&gt;
  &lt;a href=&quot;list.html&quot; th:href=&quot;@{/order/list}&quot;&gt;Return to order list&lt;/a&gt;
&lt;/p&gt;
</code></pre>

<p></body></p>

<p></html></p>

<p>Not much really new here, except for this nested object selection:</p>

<p><body th:object="${order}"></p>

<p>&hellip;</p>

<p><div th:object="*{customer}">
    <p><b>Name:</b> <span th:text="*{name}">Frederic Tomato</span></p>
    &hellip;
  </div></p>

<p>&hellip;
</body></p>

<p>…which makes that *{name} equivalent to:</p>

<p><b>Name:</b> <span th:text="${order.customer.name}">Frederic Tomato</span></p>

<p>15 More on Configuration
15.1 Template Resolvers</p>

<p>For our Good Thymes Virtual Grocery, we chose an ITemplateResolver implementation called ServletContextTemplateResolver that allowed us to obtain templates as resources from the Servlet Context.</p>

<p>Besides giving us the ability to create our own template resolver by implementing ITemplateResolver, Thymeleaf includes four implementations out of the box:</p>

<pre><code>org.thymeleaf.templateresolver.ClassLoaderTemplateResolver, which resolves templates as classloader resources, like:

return Thread.currentThread().getContextClassLoader().getResourceAsStream(template);

org.thymeleaf.templateresolver.FileTemplateResolver, which resolves templates as files from the file system, like:

return new FileInputStream(new File(template));

org.thymeleaf.templateresolver.UrlTemplateResolver, which resolves templates as URLs (even non-local ones), like:

return (new URL(template)).openStream();

org.thymeleaf.templateresolver.StringTemplateResolver, which resolves templates directly as the String being specified as template (or template name, which in this case is obviously much more than a mere name):

return new StringReader(templateName);
</code></pre>

<p>All of the pre-bundled implementations of ITemplateResolver allow the same set of configuration parameters, which include:</p>

<pre><code>Prefix and suffix (as already seen):

templateResolver.setPrefix(&quot;/WEB-INF/templates/&quot;);
templateResolver.setSuffix(&quot;.html&quot;);

Template aliases that allow the use of template names that do not directly correspond to file names. If both suffix/prefix and alias exist, alias will be applied before prefix/suffix:

templateResolver.addTemplateAlias(&quot;adminHome&quot;,&quot;profiles/admin/home&quot;);
templateResolver.setTemplateAliases(aliasesMap);

Encoding to be applied when reading templates:

templateResolver.setEncoding(&quot;UTF-8&quot;);

Template mode to be used:

// Default is HTML
templateResolver.setTemplateMode(&quot;XML&quot;);

Default mode for template cache, and patterns for defining whether specific templates are cacheable or not:

// Default is true
templateResolver.setCacheable(false);
templateResolver.getCacheablePatternSpec().addPattern(&quot;/users/*&quot;);

TTL in milliseconds for parsed template cache entries originated in this template resolver. If not set, the only way to remove an entry from the cache will be to exceed the cache max size (oldest entry will be removed).

// Default is no TTL (only cache size exceeded would remove entries)
templateResolver.setCacheTTLMs(60000L);

The Thymeleaf + Spring integration packages offer a SpringResourceTemplateResolver implementation which uses all the Spring infrastructure for accessing and reading resources in applications, and which is the recommended implementation in Spring-enabled applications.
</code></pre>

<p>Chaining Template Resolvers</p>

<p>Also, a Template Engine can specify several template resolvers, in which case an order can be established between them for template resolution so that, if the first one is not able to resolve the template, the second one is asked, and so on:</p>

<p>ClassLoaderTemplateResolver classLoaderTemplateResolver = new ClassLoaderTemplateResolver();
classLoaderTemplateResolver.setOrder(Integer.valueOf(1));</p>

<p>ServletContextTemplateResolver servletContextTemplateResolver =
        new ServletContextTemplateResolver(servletContext);
servletContextTemplateResolver.setOrder(Integer.valueOf(2));</p>

<p>templateEngine.addTemplateResolver(classLoaderTemplateResolver);
templateEngine.addTemplateResolver(servletContextTemplateResolver);</p>

<p>When several template resolvers are applied, it is recommended to specify patterns for each template resolver so that Thymeleaf can quickly discard those template resolvers that are not meant to resolve the template, enhancing performance. Doing this is not a requirement, but a recommendation:</p>

<p>ClassLoaderTemplateResolver classLoaderTemplateResolver = new ClassLoaderTemplateResolver();
classLoaderTemplateResolver.setOrder(Integer.valueOf(1));
// This classloader will not be even asked for any templates not matching these patterns
classLoaderTemplateResolver.getResolvablePatternSpec().addPattern(&ldquo;/layout/<em>.html&rdquo;);
classLoaderTemplateResolver.getResolvablePatternSpec().addPattern(&ldquo;/menu/</em>.html&rdquo;);</p>

<p>ServletContextTemplateResolver servletContextTemplateResolver =
        new ServletContextTemplateResolver(servletContext);
servletContextTemplateResolver.setOrder(Integer.valueOf(2));</p>

<p>If these resolvable patterns are not specified, we will be relying on the specific capabilities of each of the ITemplateResolver implementations we are using. Note that not all implementations might be able to determine the existence of a template before resolving, and thus could always consider a template as resolvable and break the resolution chain (not allowing other resolvers to check for the same template), but then be unable to read the real resource.</p>

<p>All the ITemplateResolver implementations that are included with core Thymeleaf include a mechanism that will allow us to make the resolvers really check if a resource exists before considering it resolvable. It is the checkExistence flag, which works like:</p>

<p>ClassLoaderTemplateResolver classLoaderTemplateResolver = new ClassLoaderTemplateResolver();
classLoaderTemplateResolver.setOrder(Integer.valueOf(1));
classLoaderTempalteResolver.setCheckExistence(true);</p>

<p>This checkExistence flag forces the resolver perform a real check for resource existence during the resolution phase (and let the following resolver in the chain be called if existence check returns false). While this might sound good in every case, in most cases this will mean a double access to the resource itself (once for checking existence, another time for reading it), and could be a performance issue in some scenarios, e.g. remote URL-based template resources – a potential performance issue that might anyway get largely mitigated by the use of the template cache (in which case templates will only be resolved the first time they are accessed).
15.2 Message Resolvers</p>

<p>We did not explicitly specify a Message Resolver implementation for our Grocery application, and as it was explained before, this meant that the implementation being used was an org.thymeleaf.messageresolver.StandardMessageResolver object.</p>

<p>StandardMessageResolver is the standard implementation of the IMessageResolver interface, but we could create our own if we wanted, adapted to the specific needs of our application.</p>

<pre><code>The Thymeleaf + Spring integration packages offer by default an IMessageResolver implementation which uses the standard Spring way of retrieving externalized messages, by using MessageSource beans declared at the Spring Application Context.
</code></pre>

<p>Standard Message Resolver</p>

<p>So how does StandardMessageResolver look for the messages requested at a specific template?</p>

<p>If the template name is home and it is located in /WEB-INF/templates/home.html, and the requested locale is gl_ES then this resolver will look for messages in the following files, in this order:</p>

<pre><code>/WEB-INF/templates/home_gl_ES.properties
/WEB-INF/templates/home_gl.properties
/WEB-INF/templates/home.properties
</code></pre>

<p>Refer to the JavaDoc documentation of the StandardMessageResolver class for more detail on how the complete message resolution mechanism works.
Configuring message resolvers</p>

<p>What if we wanted to add a message resolver (or more) to the Template Engine? Easy:</p>

<p>// For setting only one
templateEngine.setMessageResolver(messageResolver);</p>

<p>// For setting more than one
templateEngine.addMessageResolver(messageResolver);</p>

<p>And why would we want to have more than one message resolver? For the same reason as template resolvers: message resolvers are ordered and if the first one cannot resolve a specific message, the second one will be asked, then the third, etc.
15.3 Conversion Services</p>

<p>The conversion service that enables us to perform data conversion and formatting operations by means of the double-brace syntax (${{&hellip;}}) is actually a feature of the Standard Dialect, not of the Thymeleaf Template Engine itself.</p>

<p>As such, the way to configure it is by setting our custom implementation of the IStandardConversionService interface directly into the instance of StandardDialect that is being configured into the template engine. Like:</p>

<p>IStandardConversionService customConversionService = &hellip;</p>

<p>StandardDialect dialect = new StandardDialect();
dialect.setConversionService(customConversionService);</p>

<p>templateEngine.setDialect(dialect);</p>

<pre><code>Note that the thymeleaf-spring3 and thymeleaf-spring4 packages contain the SpringStandardDialect, and this dialect already comes pre-configured with an implementation of IStandardConversionService that integrates Spring’s own Conversion Service infrastructure into Thymeleaf.
</code></pre>

<p>15.4 Logging</p>

<p>Thymeleaf pays quite a lot of attention to logging, and always tries to offer the maximum amount of useful information through its logging interface.</p>

<p>The logging library used is slf4j, which in fact acts as a bridge to whichever logging implementation we might want to use in our application (for example, log4j).</p>

<p>Thymeleaf classes will log TRACE, DEBUG and INFO-level information, depending on the level of detail we desire, and besides general logging it will use three special loggers associated with the TemplateEngine class which we can configure separately for different purposes:</p>

<pre><code>org.thymeleaf.TemplateEngine.CONFIG will output detailed configuration of the library during initialization.
org.thymeleaf.TemplateEngine.TIMER will output information about the amount of time taken to process each template (useful for benchmarking!)
org.thymeleaf.TemplateEngine.cache is the prefix for a set of loggers that output specific information about the caches. Although the names of the cache loggers are configurable by the user and thus could change, by default they are:
    org.thymeleaf.TemplateEngine.cache.TEMPLATE_CACHE
    org.thymeleaf.TemplateEngine.cache.EXPRESSION_CACHE
</code></pre>

<p>An example configuration for Thymeleaf’s logging infrastructure, using log4j, could be:</p>

<p>log4j.logger.org.thymeleaf=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.CONFIG=TRACE
log4j.logger.org.thymeleaf.TemplateEngine.TIMER=TRACE
log4j.logger.org.thymeleaf.TemplateEngine.cache.TEMPLATE_CACHE=TRACE</p>

<p>16 Template Cache</p>

<p>Thymeleaf works thanks to a set of parsers – for markup and text – that parse templates into sequences of events (open tag, text, close tag, comment, etc.) and a series of processors – one for each type of behaviour that needs to be applied – that modify the template parsed event sequence in order to create the results we expect by combining the original template with our data.</p>

<p>It also includes – by default – a cache that stores parsed templates; the sequence of events resulting from reading and parsing template files before processing them. This is especially useful when working in a web application, and builds on the following concepts:</p>

<pre><code>Input/Output is almost always the slowest part of any application. In-memory processing is extremely quick by comparison.
Cloning an existing in-memory event sequence is always much quicker than reading a template file, parsing it and creating a new event sequence for it.
Web applications usually have only a few dozen templates.
Template files are small-to-medium size, and they are not modified while the application is running.
</code></pre>

<p>This all leads to the idea that caching the most used templates in a web application is feasible without wasting large amounts of memory, and also that it will save a lot of time that would be spent on input/output operations on a small set of files that, in fact, never change.</p>

<p>And how can we take control of this cache? First, we’ve learned before that we can enable or disable it at the Template Resolver, even acting only on specific templates:</p>

<p>// Default is true
templateResolver.setCacheable(false);
templateResolver.getCacheablePatternSpec().addPattern(&ldquo;/users/*&ldquo;);</p>

<p>Also, we could modify its configuration by establishing our own Cache Manager object, which could be an instance of the default StandardCacheManager implementation:</p>

<p>// Default is 200
StandardCacheManager cacheManager = new StandardCacheManager();
cacheManager.setTemplateCacheMaxSize(100);
&hellip;
templateEngine.setCacheManager(cacheManager);</p>

<p>Refer to the javadoc API of org.thymeleaf.cache.StandardCacheManager for more info on configuring the caches.</p>

<p>Entries can be manually removed from the template cache:</p>

<p>// Clear the cache completely
templateEngine.clearTemplateCache();</p>

<p>// Clear a specific template from the cache
templateEngine.clearTemplateCacheFor(&ldquo;/users/userList&rdquo;);</p>

<p>17 Decoupled Template Logic
17.1 Decoupled logic: The concept</p>

<p>So far we have worked for our Grocery Store with templates done the usual way, with logic being inserted into our templates in the form of attributes.</p>

<p>But Thymeleaf also allows us to completely decouple the template markup from its logic, allowing the creation of completely logic-less markup templates in the HTML and XML template modes.</p>

<p>The main idea is that template logic will be defined in a separate logic file (more exactly a logic resource, as it doesn’t need to be a file). By default, that logic resource will be an additional file living in the same place ( e.g. folder) as the template file, with the same name but with .th.xml extension:</p>

<p>/templates
+-&gt;/home.html
+-&gt;/home.th.xml</p>

<p>So the home.html file can be completely logic-less. It might look like this:</p>

<p>&lt;!DOCTYPE html&gt;
<html>
  <body>
    <table id="usersTable">
      <tr>
        <td class="username">Jeremy Grapefruit</td>
        <td class="usertype">Normal User</td>
      </tr>
      <tr>
        <td class="username">Alice Watermelon</td>
        <td class="usertype">Administrator</td>
      </tr>
    </table>
  </body>
</html></p>

<p>Absolutely no Thymeleaf code there. This is a template file that a designer with no Thymeleaf or templating knowledge could have created, edited and/or understood. Or a fragment of HTML provided by some external system with no Thymeleaf hooks at all.</p>

<p>Let’s now turn that home.html template into a Thymeleaf template by creating our additional home.th.xml file like this:</p>

<p>&lt;?xml version=&ldquo;1.0&rdquo;?&gt;
<thlogic>
  <attr sel="#usersTable" th:remove="all-but-first">
    <attr sel="/tr[0]" th:each="user : ${users}">
      <attr sel="td.username" th:text="${user.name}" />
      <attr sel="td.usertype" th:text="#{|user.type.${user.type}|}" />
    </attr>
  </attr>
</thlogic></p>

<p>Here we can see a lot of <attr> tags inside a thlogic block. Those <attr> tags perform attribute injection on nodes of the original template selected by means of their sel attributes, which contain Thymeleaf markup selectors (actually AttoParser markup selectors).</p>

<p>Also note that <attr> tags can be nested so that their selectors are appended. That sel=&ldquo;/tr[0]&rdquo; above, for example, will be processed as sel=&ldquo;#usersTable/tr[0]&ldquo;. And the selector for the user name <td> will be processed as sel=&ldquo;#usersTable/tr[0]//td.username&rdquo;.</p>

<p>So once merged, both files seen above will be the same as:</p>

<p>&lt;!DOCTYPE html&gt;
<html>
  <body>
    <table id="usersTable" th:remove="all-but-first">
      <tr th:each="user : ${users}">
        <td class="username" th:text="${user.name}">Jeremy Grapefruit</td>
        <td class="usertype" th:text="#{|user.type.${user.type}|}">Normal User</td>
      </tr>
      <tr>
        <td class="username">Alice Watermelon</td>
        <td class="usertype">Administrator</td>
      </tr>
    </table>
  </body>
</html></p>

<p>This looks more familiar, and is indeed less verbose than creating two separate files. But the advantage of decoupled templates is that we can give for our templates total independence from Thymeleaf, and therefore better maintainability from the design standpoint.</p>

<p>Of course some contracts between designers or developers will still be needed – e.g. the fact that the users <table> will need an id=&ldquo;usersTable&rdquo; –, but in many scenarios a pure-HTML template will be a much better communication artifact between design and development teams.
17.2 Configuring decoupled templates
Enabling decoupled templates</p>

<p>Decoupled logic will not be expected for every template by default. Instead, the configured template resolvers (implementations of ITemplateResolver) will need to specifically mark the templates they resolve as using decoupled logic.</p>

<p>Except for StringTemplateResolver (which does not allow decoupled logic), all other out-of-the-box implementations of ITemplateResolver will provide a flag called useDecoupledLogic that will mark all templates resolved by that resolver as potentially having all or part of its logic living in a separate resource:</p>

<p>final ServletContextTemplateResolver templateResolver =
        new ServletContextTemplateResolver(servletContext);
&hellip;
templateResolver.setUseDecoupledLogic(true);</p>

<p>Mixing coupled and decoupled logic</p>

<p>Decoupled template logic, when enabled, is not a requirement. When enabled, it means that the engine will look for a resource containing decoupled logic, parsing and merging it with the original template if it exists. No error will be thrown if the decoupled logic resource does not exist.</p>

<p>Also, in the same template we can mix both coupled and decoupled logic, for example by adding some Thymeleaf attributes at the original template file but leaving others for the separate decoupled logic file. The most common case for this is using the new (in v3.0) th:ref attribute.
17.3 The th:ref attribute</p>

<p>th:ref is only a marker attribute. It does nothing from the processing standpoint and simply disappears when the template is processed, but its usefulness lies in the fact that it acts as a markup reference, i.e. it can be resolved by name from a markup selector just like a tag name or a fragment (th:fragment).</p>

<p>So if we have a selector like:</p>

<p><attr sel="whatever" .../></p>

<p>This will match:</p>

<pre><code>Any &lt;whatever&gt; tags.
Any tags with a th:fragment=&quot;whatever&quot; attribute.
Any tags with a th:ref=&quot;whatever&quot; attribute.
</code></pre>

<p>What is the advantage of th:ref against, for example, using a pure-HTML id attribute? Merely the fact that we might not want to add so many id and class attributes to our tags to act as logic anchors, which might end up polluting our output.</p>

<p>And in the same sense, what is the disadvantage of th:ref? Well, obviously that we’d be adding a bit of Thymeleaf logic (“logic”) to our templates.</p>

<p>Note this applicability of the th:ref attribute does not only apply to decoupled logic template files: it works the same in other types of scenarios, like in fragment expressions (~{&hellip;}).
17.4 Performance impact of decoupled templates</p>

<p>The impact is extremely small. When a resolved template is marked to use decoupled logic and it is not cached, the template logic resource will be resolved first, parsed and processed into a secuence of instructions in-memory: basically a list of attributes to be injected to each markup selector.</p>

<p>But this is the only additional step required because, after this, the real template will be parsed, and while it is parsed these attributes will be injected on-the-fly by the parser itself, thanks to the advanced capabilities for node selection in AttoParser. So parsed nodes will come out of the parser as if they had their injected attributes written in the original template file.</p>

<p>The biggest advantage of this? When a template is configured to be cached, it will be cached already containing the injected attributes. So the overhead of using decoupled templates for cacheable templates, once they are cached, will be absolutely zero.
17.5 Resolution of decoupled logic</p>

<p>The way Thymeleaf resolves the decoupled logic resources corresponding to each template is configurable by the user. It is determined by an extension point, the org.thymeleaf.templateparser.markup.decoupled.IDecoupledTemplateLogicResolver, for which a default implementation is provided: StandardDecoupledTemplateLogicResolver.</p>

<p>What does this standard implementation do?</p>

<pre><code>First, it applies a prefix and a suffix to the base name of the template resource (obtained by means of its ITemplateResource#getBaseName() method). Both prefix and suffix can be configured and, by default, the prefix will be empty and the suffix will be .th.xml.
Second, it asks the template resource to resolve a relative resource with the computed name by means of its ITemplateResource#relative(String relativeLocation) method.
</code></pre>

<p>The specific implementation of IDecoupledTemplateLogicResolver to be used can be configured at the TemplateEngine easily:</p>

<p>final StandardDecoupledTemplateLogicResolver decoupledresolver =
        new StandardDecoupledTemplateLogicResolver();
decoupledResolver.setPrefix(&ldquo;../viewlogic/&rdquo;);
&hellip;
templateEngine.setDecoupledTemplateLogicResolver(decoupledResolver);</p>

<p>18 Appendix A: Expression Basic Objects</p>

<p>Some objects and variable maps are always available to be invoked. Let’s see them:
Base objects</p>

<pre><code>#ctx : the context object. An implementation of org.thymeleaf.context.IContext or org.thymeleaf.context.IWebContext depending on our environment (standalone or web).

Note #vars and #root are synomyns for the same object, but using #ctx is recommended.
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.context.IContext
 * ======================================================================
 */</p>

<p>${#ctx.locale}
${#ctx.variableNames}</p>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.context.IWebContext
 * ======================================================================
 */</p>

<p>${#ctx.request}
${#ctx.response}
${#ctx.session}
${#ctx.servletContext}</p>

<pre><code>#locale : direct access to the java.util.Locale associated with current request.
</code></pre>

<p>${#locale}</p>

<p>Web context namespaces for request/session attributes, etc.</p>

<p>When using Thymeleaf in a web environment, we can use a series of shortcuts for accessing request parameters, session attributes and application attributes:</p>

<pre><code>Note these are not context objects, but maps added to the context as variables, so we access them without #. In some way, they act as namespaces.

param : for retrieving request parameters. ${param.foo} is a String[] with the values of the foo request parameter, so ${param.foo[0]} will normally be used for getting the first value.
</code></pre>

<p>/*
 * ============================================================================
 * See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap
 * ============================================================================
 */</p>

<p>${param.foo}              // Retrieves a String[] with the values of request parameter &lsquo;foo&rsquo;
${param.size()}
${param.isEmpty()}
${param.containsKey(&lsquo;foo&rsquo;)}
&hellip;</p>

<pre><code>session : for retrieving session attributes.
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.context.WebSessionVariablesMap
 * ======================================================================
 */</p>

<p>${session.foo}                 // Retrieves the session atttribute &lsquo;foo&rsquo;
${session.size()}
${session.isEmpty()}
${session.containsKey(&lsquo;foo&rsquo;)}
&hellip;</p>

<pre><code>application : for retrieving application/servlet context attributes.
</code></pre>

<p>/*
 * =============================================================================
 * See javadoc API for class org.thymeleaf.context.WebServletContextVariablesMap
 * =============================================================================
 */</p>

<p>${application.foo}              // Retrieves the ServletContext atttribute &lsquo;foo&rsquo;
${application.size()}
${application.isEmpty()}
${application.containsKey(&lsquo;foo&rsquo;)}
&hellip;</p>

<p>Note there is no need to specify a namespace for accessing request attributes (as opposed to request parameters) because all request attributes are automatically added to the context as variables in the context root:</p>

<p>${myRequestAttribute}</p>

<p>Web context objects</p>

<p>Inside a web environment there is also direct access to the following objects (note these are objects, not maps/namespaces):</p>

<pre><code>#request : direct access to the javax.servlet.http.HttpServletRequest object associated with the current request.
</code></pre>

<p>${#request.getAttribute(&lsquo;foo&rsquo;)}
${#request.getParameter(&lsquo;foo&rsquo;)}
${#request.getContextPath()}
${#request.getRequestName()}
&hellip;</p>

<pre><code>#session : direct access to the javax.servlet.http.HttpSession object associated with the current request.
</code></pre>

<p>${#session.getAttribute(&lsquo;foo&rsquo;)}
${#session.id}
${#session.lastAccessedTime}
&hellip;</p>

<pre><code>#servletContext : direct access to the javax.servlet.ServletContext object associated with the current request.
</code></pre>

<p>${#servletContext.getAttribute(&lsquo;foo&rsquo;)}
${#servletContext.contextPath}
&hellip;</p>

<p>19 Appendix B: Expression Utility Objects
Execution Info</p>

<pre><code>#execInfo : expression object providing useful information about the template being processed inside Thymeleaf Standard Expressions.
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.ExecutionInfo
 * ======================================================================
 */</p>

<p>/*
 * Return the name and mode of the &lsquo;leaf&rsquo; template. This means the template
 * from where the events being processed were parsed. So if this piece of
 * code is not in the root template &ldquo;A&rdquo; but on a fragment being inserted
 * into &ldquo;A&rdquo; from another template called &ldquo;B&rdquo;, this will return &ldquo;B&rdquo; as a
 * name, and B&rsquo;s mode as template mode.
 */
${#execInfo.templateName}
${#execInfo.templateMode}</p>

<p>/*
 * Return the name and mode of the &lsquo;root&rsquo; template. This means the template
 * that the template engine was originally asked to process. So if this
 * piece of code is not in the root template &ldquo;A&rdquo; but on a fragment being
 * inserted into &ldquo;A&rdquo; from another template called &ldquo;B&rdquo;, this will still
 * return &ldquo;A&rdquo; and A&rsquo;s template mode.
 */
${#execInfo.processedTemplateName}
${#execInfo.processedTemplateMode}</p>

<p>/*
 * Return the stacks (actually, List<String> or List<TemplateMode>) of
 * templates being processed. The first element will be the
 * &lsquo;processedTemplate&rsquo; (the root one), the last one will be the &lsquo;leaf&rsquo;
 * template, and in the middle all the fragments inserted in nested
 * manner to reach the leaf from the root will appear.
 */
${#execInfo.templateNames}
${#execInfo.templateModes}</p>

<p>/*
 * Return the stack of templates being processed similarly (and in the
 * same order) to &lsquo;templateNames&rsquo; and &lsquo;templateModes&rsquo;, but returning
 * a List<TemplateData> with the full template metadata.
 */
${#execInfo.templateStack}</p>

<p>Messages</p>

<pre><code>#messages : utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{...} syntax.
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Messages
 * ======================================================================
 */</p>

<p>/*
 * Obtain externalized messages. Can receive a single key, a key plus arguments,
 * or an array/list/set of keys (in which case it will return an array/list/set of
 * externalized messages).
 * If a message is not found, a default message (like &lsquo;??msgKey??&rsquo;) is returned.
 */
${#messages.msg(&lsquo;msgKey&rsquo;)}
${#messages.msg(&lsquo;msgKey&rsquo;, param1)}
${#messages.msg(&lsquo;msgKey&rsquo;, param1, param2)}
${#messages.msg(&lsquo;msgKey&rsquo;, param1, param2, param3)}
${#messages.msgWithParams(&lsquo;msgKey&rsquo;, new Object[] {param1, param2, param3, param4})}
${#messages.arrayMsg(messageKeyArray)}
${#messages.listMsg(messageKeyList)}
${#messages.setMsg(messageKeySet)}</p>

<p>/*
 * Obtain externalized messages or null. Null is returned instead of a default
 * message if a message for the specified key is not found.
 */
${#messages.msgOrNull(&lsquo;msgKey&rsquo;)}
${#messages.msgOrNull(&lsquo;msgKey&rsquo;, param1)}
${#messages.msgOrNull(&lsquo;msgKey&rsquo;, param1, param2)}
${#messages.msgOrNull(&lsquo;msgKey&rsquo;, param1, param2, param3)}
${#messages.msgOrNullWithParams(&lsquo;msgKey&rsquo;, new Object[] {param1, param2, param3, param4})}
${#messages.arrayMsgOrNull(messageKeyArray)}
${#messages.listMsgOrNull(messageKeyList)}
${#messages.setMsgOrNull(messageKeySet)}</p>

<p>URIs/URLs</p>

<pre><code>#uris : utility object for performing URI/URL operations ( esp. escaping/unescaping) inside Thymeleaf Standard Expressions.
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Uris
 * ======================================================================
 */</p>

<p>/*
 * Escape/Unescape as a URI/URL path
 */
${#uris.escapePath(uri)}
${#uris.escapePath(uri, encoding)}
${#uris.unescapePath(uri)}
${#uris.unescapePath(uri, encoding)}</p>

<p>/*
 * Escape/Unescape as a URI/URL path segment (between &lsquo;/&rsquo; symbols)
 */
${#uris.escapePathSegment(uri)}
${#uris.escapePathSegment(uri, encoding)}
${#uris.unescapePathSegment(uri)}
${#uris.unescapePathSegment(uri, encoding)}</p>

<p>/*
 * Escape/Unescape as a Fragment Identifier (#frag)
 */
${#uris.escapeFragmentId(uri)}
${#uris.escapeFragmentId(uri, encoding)}
${#uris.unescapeFragmentId(uri)}
${#uris.unescapeFragmentId(uri, encoding)}</p>

<p>/*
 * Escape/Unescape as a Query Parameter (?var=value)
 */
${#uris.escapeQueryParam(uri)}
${#uris.escapeQueryParam(uri, encoding)}
${#uris.unescapeQueryParam(uri)}
${#uris.unescapeQueryParam(uri, encoding)}</p>

<p>Conversions</p>

<pre><code>#conversions : utility object that allows the execution of the Conversion Service at any point of a template:
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Conversions
 * ======================================================================
 */</p>

<p>/*
 * Execute the desired conversion of the &lsquo;object&rsquo; value into the
 * specified class.
 */
${#conversions.convert(object, &lsquo;java.util.TimeZone&rsquo;)}
${#conversions.convert(object, targetClass)}</p>

<p>Dates</p>

<pre><code>#dates : utility methods for java.util.Date objects:
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Dates
 * ======================================================================
 */</p>

<p>/*
 * Format date with the standard locale format
 * Also works with arrays, lists or sets
 */
${#dates.format(date)}
${#dates.arrayFormat(datesArray)}
${#dates.listFormat(datesList)}
${#dates.setFormat(datesSet)}</p>

<p>/*
 * Format date with the ISO8601 format
 * Also works with arrays, lists or sets
 */
${#dates.formatISO(date)}
${#dates.arrayFormatISO(datesArray)}
${#dates.listFormatISO(datesList)}
${#dates.setFormatISO(datesSet)}</p>

<p>/*
 * Format date with the specified pattern
 * Also works with arrays, lists or sets
 */
${#dates.format(date, &lsquo;dd/MMM/yyyy HH:mm&rsquo;)}
${#dates.arrayFormat(datesArray, &lsquo;dd/MMM/yyyy HH:mm&rsquo;)}
${#dates.listFormat(datesList, &lsquo;dd/MMM/yyyy HH:mm&rsquo;)}
${#dates.setFormat(datesSet, &lsquo;dd/MMM/yyyy HH:mm&rsquo;)}</p>

<p>/*
 * Obtain date properties
 * Also works with arrays, lists or sets
 */
${#dates.day(date)}                    // also arrayDay(&hellip;), listDay(&hellip;), etc.
${#dates.month(date)}                  // also arrayMonth(&hellip;), listMonth(&hellip;), etc.
${#dates.monthName(date)}              // also arrayMonthName(&hellip;), listMonthName(&hellip;), etc.
${#dates.monthNameShort(date)}         // also arrayMonthNameShort(&hellip;), listMonthNameShort(&hellip;), etc.
${#dates.year(date)}                   // also arrayYear(&hellip;), listYear(&hellip;), etc.
${#dates.dayOfWeek(date)}              // also arrayDayOfWeek(&hellip;), listDayOfWeek(&hellip;), etc.
${#dates.dayOfWeekName(date)}          // also arrayDayOfWeekName(&hellip;), listDayOfWeekName(&hellip;), etc.
${#dates.dayOfWeekNameShort(date)}     // also arrayDayOfWeekNameShort(&hellip;), listDayOfWeekNameShort(&hellip;), etc.
${#dates.hour(date)}                   // also arrayHour(&hellip;), listHour(&hellip;), etc.
${#dates.minute(date)}                 // also arrayMinute(&hellip;), listMinute(&hellip;), etc.
${#dates.second(date)}                 // also arraySecond(&hellip;), listSecond(&hellip;), etc.
${#dates.millisecond(date)}            // also arrayMillisecond(&hellip;), listMillisecond(&hellip;), etc.</p>

<p>/*
 * Create date (java.util.Date) objects from its components
 */
${#dates.create(year,month,day)}
${#dates.create(year,month,day,hour,minute)}
${#dates.create(year,month,day,hour,minute,second)}
${#dates.create(year,month,day,hour,minute,second,millisecond)}</p>

<p>/*
 * Create a date (java.util.Date) object for the current date and time
 */
${#dates.createNow()}</p>

<p>${#dates.createNowForTimeZone()}</p>

<p>/*
 * Create a date (java.util.Date) object for the current date (time set to 00:00)
 */
${#dates.createToday()}</p>

<p>${#dates.createTodayForTimeZone()}</p>

<p>Calendars</p>

<pre><code>#calendars : analogous to #dates, but for java.util.Calendar objects:
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Calendars
 * ======================================================================
 */</p>

<p>/*
 * Format calendar with the standard locale format
 * Also works with arrays, lists or sets
 */
${#calendars.format(cal)}
${#calendars.arrayFormat(calArray)}
${#calendars.listFormat(calList)}
${#calendars.setFormat(calSet)}</p>

<p>/*
 * Format calendar with the ISO8601 format
 * Also works with arrays, lists or sets
 */
${#calendars.formatISO(cal)}
${#calendars.arrayFormatISO(calArray)}
${#calendars.listFormatISO(calList)}
${#calendars.setFormatISO(calSet)}</p>

<p>/*
 * Format calendar with the specified pattern
 * Also works with arrays, lists or sets
 */
${#calendars.format(cal, &lsquo;dd/MMM/yyyy HH:mm&rsquo;)}
${#calendars.arrayFormat(calArray, &lsquo;dd/MMM/yyyy HH:mm&rsquo;)}
${#calendars.listFormat(calList, &lsquo;dd/MMM/yyyy HH:mm&rsquo;)}
${#calendars.setFormat(calSet, &lsquo;dd/MMM/yyyy HH:mm&rsquo;)}</p>

<p>/*
 * Obtain calendar properties
 * Also works with arrays, lists or sets
 */
${#calendars.day(date)}                // also arrayDay(&hellip;), listDay(&hellip;), etc.
${#calendars.month(date)}              // also arrayMonth(&hellip;), listMonth(&hellip;), etc.
${#calendars.monthName(date)}          // also arrayMonthName(&hellip;), listMonthName(&hellip;), etc.
${#calendars.monthNameShort(date)}     // also arrayMonthNameShort(&hellip;), listMonthNameShort(&hellip;), etc.
${#calendars.year(date)}               // also arrayYear(&hellip;), listYear(&hellip;), etc.
${#calendars.dayOfWeek(date)}          // also arrayDayOfWeek(&hellip;), listDayOfWeek(&hellip;), etc.
${#calendars.dayOfWeekName(date)}      // also arrayDayOfWeekName(&hellip;), listDayOfWeekName(&hellip;), etc.
${#calendars.dayOfWeekNameShort(date)} // also arrayDayOfWeekNameShort(&hellip;), listDayOfWeekNameShort(&hellip;), etc.
${#calendars.hour(date)}               // also arrayHour(&hellip;), listHour(&hellip;), etc.
${#calendars.minute(date)}             // also arrayMinute(&hellip;), listMinute(&hellip;), etc.
${#calendars.second(date)}             // also arraySecond(&hellip;), listSecond(&hellip;), etc.
${#calendars.millisecond(date)}        // also arrayMillisecond(&hellip;), listMillisecond(&hellip;), etc.</p>

<p>/*
 * Create calendar (java.util.Calendar) objects from its components
 */
${#calendars.create(year,month,day)}
${#calendars.create(year,month,day,hour,minute)}
${#calendars.create(year,month,day,hour,minute,second)}
${#calendars.create(year,month,day,hour,minute,second,millisecond)}</p>

<p>${#calendars.createForTimeZone(year,month,day,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,second,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,second,millisecond,timeZone)}</p>

<p>/*
 * Create a calendar (java.util.Calendar) object for the current date and time
 */
${#calendars.createNow()}</p>

<p>${#calendars.createNowForTimeZone()}</p>

<p>/*
 * Create a calendar (java.util.Calendar) object for the current date (time set to 00:00)
 */
${#calendars.createToday()}</p>

<p>${#calendars.createTodayForTimeZone()}</p>

<p>Numbers</p>

<pre><code>#numbers : utility methods for number objects:
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Numbers
 * ======================================================================
 */</p>

<p>/*
 * ==========================
 * Formatting integer numbers
 * ==========================
 */</p>

<p>/*
 * Set minimum integer digits.
 * Also works with arrays, lists or sets
 */
${#numbers.formatInteger(num,3)}
${#numbers.arrayFormatInteger(numArray,3)}
${#numbers.listFormatInteger(numList,3)}
${#numbers.setFormatInteger(numSet,3)}</p>

<p>/*
 * Set minimum integer digits and thousands separator:
 * &lsquo;POINT&rsquo;, &lsquo;COMMA&rsquo;, &lsquo;WHITESPACE&rsquo;, &lsquo;NONE&rsquo; or &lsquo;DEFAULT&rsquo; (by locale).
 * Also works with arrays, lists or sets
 */
${#numbers.formatInteger(num,3,&lsquo;POINT&rsquo;)}
${#numbers.arrayFormatInteger(numArray,3,&lsquo;POINT&rsquo;)}
${#numbers.listFormatInteger(numList,3,&lsquo;POINT&rsquo;)}
${#numbers.setFormatInteger(numSet,3,&lsquo;POINT&rsquo;)}</p>

<p>/*
 * ==========================
 * Formatting decimal numbers
 * ==========================
 */</p>

<p>/*
 * Set minimum integer digits and (exact) decimal digits.
 * Also works with arrays, lists or sets
 */
${#numbers.formatDecimal(num,3,2)}
${#numbers.arrayFormatDecimal(numArray,3,2)}
${#numbers.listFormatDecimal(numList,3,2)}
${#numbers.setFormatDecimal(numSet,3,2)}</p>

<p>/*
 * Set minimum integer digits and (exact) decimal digits, and also decimal separator.
 * Also works with arrays, lists or sets
 */
${#numbers.formatDecimal(num,3,2,&lsquo;COMMA&rsquo;)}
${#numbers.arrayFormatDecimal(numArray,3,2,&lsquo;COMMA&rsquo;)}
${#numbers.listFormatDecimal(numList,3,2,&lsquo;COMMA&rsquo;)}
${#numbers.setFormatDecimal(numSet,3,2,&lsquo;COMMA&rsquo;)}</p>

<p>/*
 * Set minimum integer digits and (exact) decimal digits, and also thousands and
 * decimal separator.
 * Also works with arrays, lists or sets
 */
${#numbers.formatDecimal(num,3,&lsquo;POINT&rsquo;,2,&lsquo;COMMA&rsquo;)}
${#numbers.arrayFormatDecimal(numArray,3,&lsquo;POINT&rsquo;,2,&lsquo;COMMA&rsquo;)}
${#numbers.listFormatDecimal(numList,3,&lsquo;POINT&rsquo;,2,&lsquo;COMMA&rsquo;)}
${#numbers.setFormatDecimal(numSet,3,&lsquo;POINT&rsquo;,2,&lsquo;COMMA&rsquo;)}</p>

<p>/*
 * =====================
 * Formatting currencies
 * =====================
 */</p>

<p>${#numbers.formatCurrency(num)}
${#numbers.arrayFormatCurrency(numArray)}
${#numbers.listFormatCurrency(numList)}
${#numbers.setFormatCurrency(numSet)}</p>

<p>/*
 * ======================
 * Formatting percentages
 * ======================
 */</p>

<p>${#numbers.formatPercent(num)}
${#numbers.arrayFormatPercent(numArray)}
${#numbers.listFormatPercent(numList)}
${#numbers.setFormatPercent(numSet)}</p>

<p>/*
 * Set minimum integer digits and (exact) decimal digits.
 */
${#numbers.formatPercent(num, 3, 2)}
${#numbers.arrayFormatPercent(numArray, 3, 2)}
${#numbers.listFormatPercent(numList, 3, 2)}
${#numbers.setFormatPercent(numSet, 3, 2)}</p>

<p>/*
 * ===============
 * Utility methods
 * ===============
 */</p>

<p>/*
 * Create a sequence (array) of integer numbers going
 * from x to y
 */
${#numbers.sequence(from,to)}
${#numbers.sequence(from,to,step)}</p>

<p>Strings</p>

<pre><code>#strings : utility methods for String objects:
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Strings
 * ======================================================================
 */</p>

<p>/*
 * Null-safe toString()
 <em>/
${#strings.toString(obj)}                           // also array</em>, list* and set*</p>

<p>/*
 * Check whether a String is empty (or null). Performs a trim() operation before check
 * Also works with arrays, lists or sets
 */
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}</p>

<p>/*
 * Perform an &lsquo;isEmpty()&rsquo; check on a string and return it if false, defaulting to
 * another specified string if true.
 * Also works with arrays, lists or sets
 */
${#strings.defaultString(text,default)}
${#strings.arrayDefaultString(textArr,default)}
${#strings.listDefaultString(textList,default)}
${#strings.setDefaultString(textSet,default)}</p>

<p>/*
 * Check whether a fragment is contained in a String
 * Also works with arrays, lists or sets
 <em>/
${#strings.contains(name,&lsquo;ez&rsquo;)}                     // also array</em>, list* and set*
${#strings.containsIgnoreCase(name,&lsquo;ez&rsquo;)}           // also array<em>, list</em> and set*</p>

<p>/*
 * Check whether a String starts or ends with a fragment
 * Also works with arrays, lists or sets
 <em>/
${#strings.startsWith(name,&lsquo;Don&rsquo;)}                  // also array</em>, list* and set*
${#strings.endsWith(name,endingFragment)}           // also array<em>, list</em> and set*</p>

<p>/*
 * Substring-related operations
 * Also works with arrays, lists or sets
 <em>/
${#strings.indexOf(name,frag)}                      // also array</em>, list* and set*
${#strings.substring(name,3,5)}                     // also array<em>, list</em> and set*
${#strings.substringAfter(name,prefix)}             // also array<em>, list</em> and set*
${#strings.substringBefore(name,suffix)}            // also array<em>, list</em> and set*
${#strings.replace(name,&lsquo;las&rsquo;,&lsquo;ler&rsquo;)}               // also array<em>, list</em> and set*</p>

<p>/*
 * Append and prepend
 * Also works with arrays, lists or sets
 <em>/
${#strings.prepend(str,prefix)}                     // also array</em>, list* and set*
${#strings.append(str,suffix)}                      // also array<em>, list</em> and set*</p>

<p>/*
 * Change case
 * Also works with arrays, lists or sets
 <em>/
${#strings.toUpperCase(name)}                       // also array</em>, list* and set*
${#strings.toLowerCase(name)}                       // also array<em>, list</em> and set*</p>

<p>/*
 * Split and join
 */
${#strings.arrayJoin(namesArray,&lsquo;,&rsquo;)}
${#strings.listJoin(namesList,&lsquo;,&rsquo;)}
${#strings.setJoin(namesSet,&lsquo;,&rsquo;)}
${#strings.arraySplit(namesStr,&lsquo;,&rsquo;)}                // returns String[]
${#strings.listSplit(namesStr,&lsquo;,&rsquo;)}                 // returns List<String>
${#strings.setSplit(namesStr,&lsquo;,&rsquo;)}                  // returns Set<String></p>

<p>/*
 * Trim
 * Also works with arrays, lists or sets
 <em>/
${#strings.trim(str)}                               // also array</em>, list* and set*</p>

<p>/*
 * Compute length
 * Also works with arrays, lists or sets
 <em>/
${#strings.length(str)}                             // also array</em>, list* and set*</p>

<p>/*
 * Abbreviate text making it have a maximum size of n. If text is bigger, it
 * will be clipped and finished in &ldquo;&hellip;&rdquo;
 * Also works with arrays, lists or sets
 <em>/
${#strings.abbreviate(str,10)}                      // also array</em>, list* and set*</p>

<p>/*
 * Convert the first character to upper-case (and vice-versa)
 <em>/
${#strings.capitalize(str)}                         // also array</em>, list* and set*
${#strings.unCapitalize(str)}                       // also array<em>, list</em> and set*</p>

<p>/*
 * Convert the first character of every word to upper-case
 <em>/
${#strings.capitalizeWords(str)}                    // also array</em>, list* and set*
${#strings.capitalizeWords(str,delimiters)}         // also array<em>, list</em> and set*</p>

<p>/*
 * Escape the string
 <em>/
${#strings.escapeXml(str)}                          // also array</em>, list* and set*
${#strings.escapeJava(str)}                         // also array<em>, list</em> and set*
${#strings.escapeJavaScript(str)}                   // also array<em>, list</em> and set*
${#strings.unescapeJava(str)}                       // also array<em>, list</em> and set*
${#strings.unescapeJavaScript(str)}                 // also array<em>, list</em> and set*</p>

<p>/*
 * Null-safe comparison and concatenation
 */
${#strings.equals(first, second)}
${#strings.equalsIgnoreCase(first, second)}
${#strings.concat(values&hellip;)}
${#strings.concatReplaceNulls(nullValue, values&hellip;)}</p>

<p>/*
 * Random
 */
${#strings.randomAlphanumeric(count)}</p>

<p>Objects</p>

<pre><code>#objects : utility methods for objects in general
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Objects
 * ======================================================================
 */</p>

<p>/*
 * Return obj if it is not null, and default otherwise
 * Also works with arrays, lists or sets
 */
${#objects.nullSafe(obj,default)}
${#objects.arrayNullSafe(objArray,default)}
${#objects.listNullSafe(objList,default)}
${#objects.setNullSafe(objSet,default)}</p>

<p>Booleans</p>

<pre><code>#bools : utility methods for boolean evaluation
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Bools
 * ======================================================================
 */</p>

<p>/*
 * Evaluate a condition in the same way that it would be evaluated in a th:if tag
 * (see conditional evaluation chapter afterwards).
 * Also works with arrays, lists or sets
 */
${#bools.isTrue(obj)}
${#bools.arrayIsTrue(objArray)}
${#bools.listIsTrue(objList)}
${#bools.setIsTrue(objSet)}</p>

<p>/*
 * Evaluate with negation
 * Also works with arrays, lists or sets
 */
${#bools.isFalse(cond)}
${#bools.arrayIsFalse(condArray)}
${#bools.listIsFalse(condList)}
${#bools.setIsFalse(condSet)}</p>

<p>/*
 * Evaluate and apply AND operator
 * Receive an array, a list or a set as parameter
 */
${#bools.arrayAnd(condArray)}
${#bools.listAnd(condList)}
${#bools.setAnd(condSet)}</p>

<p>/*
 * Evaluate and apply OR operator
 * Receive an array, a list or a set as parameter
 */
${#bools.arrayOr(condArray)}
${#bools.listOr(condList)}
${#bools.setOr(condSet)}</p>

<p>Arrays</p>

<pre><code>#arrays : utility methods for arrays
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Arrays
 * ======================================================================
 */</p>

<p>/*
 * Converts to array, trying to infer array component class.
 * Note that if resulting array is empty, or if the elements
 * of the target object are not all of the same class,
 * this method will return Object[].
 */
${#arrays.toArray(object)}</p>

<p>/*
 * Convert to arrays of the specified component class.
 */
${#arrays.toStringArray(object)}
${#arrays.toIntegerArray(object)}
${#arrays.toLongArray(object)}
${#arrays.toDoubleArray(object)}
${#arrays.toFloatArray(object)}
${#arrays.toBooleanArray(object)}</p>

<p>/*
 * Compute length
 */
${#arrays.length(array)}</p>

<p>/*
 * Check whether array is empty
 */
${#arrays.isEmpty(array)}</p>

<p>/*
 * Check if element or elements are contained in array
 */
${#arrays.contains(array, element)}
${#arrays.containsAll(array, elements)}</p>

<p>Lists</p>

<pre><code>#lists : utility methods for lists
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Lists
 * ======================================================================
 */</p>

<p>/*
 * Converts to list
 */
${#lists.toList(object)}</p>

<p>/*
 * Compute size
 */
${#lists.size(list)}</p>

<p>/*
 * Check whether list is empty
 */
${#lists.isEmpty(list)}</p>

<p>/*
 * Check if element or elements are contained in list
 */
${#lists.contains(list, element)}
${#lists.containsAll(list, elements)}</p>

<p>/*
 * Sort a copy of the given list. The members of the list must implement
 * comparable or you must define a comparator.
 */
${#lists.sort(list)}
${#lists.sort(list, comparator)}</p>

<p>Sets</p>

<pre><code>#sets : utility methods for sets
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Sets
 * ======================================================================
 */</p>

<p>/*
 * Converts to set
 */
${#sets.toSet(object)}</p>

<p>/*
 * Compute size
 */
${#sets.size(set)}</p>

<p>/*
 * Check whether set is empty
 */
${#sets.isEmpty(set)}</p>

<p>/*
 * Check if element or elements are contained in set
 */
${#sets.contains(set, element)}
${#sets.containsAll(set, elements)}</p>

<p>Maps</p>

<pre><code>#maps : utility methods for maps
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Maps
 * ======================================================================
 */</p>

<p>/*
 * Compute size
 */
${#maps.size(map)}</p>

<p>/*
 * Check whether map is empty
 */
${#maps.isEmpty(map)}</p>

<p>/*
 * Check if key/s or value/s are contained in maps
 */
${#maps.containsKey(map, key)}
${#maps.containsAllKeys(map, keys)}
${#maps.containsValue(map, value)}
${#maps.containsAllValues(map, value)}</p>

<p>Aggregates</p>

<pre><code>#aggregates : utility methods for creating aggregates on arrays or collections
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Aggregates
 * ======================================================================
 */</p>

<p>/*
 * Compute sum. Returns null if array or collection is empty
 */
${#aggregates.sum(array)}
${#aggregates.sum(collection)}</p>

<p>/*
 * Compute average. Returns null if array or collection is empty
 */
${#aggregates.avg(array)}
${#aggregates.avg(collection)}</p>

<p>IDs</p>

<pre><code>#ids : utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
</code></pre>

<p>/*
 * ======================================================================
 * See javadoc API for class org.thymeleaf.expression.Ids
 * ======================================================================
 */</p>

<p>/*
 * Normally used in th:id attributes, for appending a counter to the id attribute value
 * so that it remains unique even when involved in an iteration process.
 */
${#ids.seq(&lsquo;someId&rsquo;)}</p>

<p>/*
 * Normally used in th:for attributes in <label> tags, so that these labels can refer to Ids
 * generated by means if the #ids.seq(&hellip;) function.
 *
 * Depending on whether the <label> goes before or after the element with the #ids.seq(&hellip;)
 * function, the &ldquo;next&rdquo; (label goes before &ldquo;seq&rdquo;) or the &ldquo;prev&rdquo; function (label goes after
 * &ldquo;seq&rdquo;) function should be called.
 */
${#ids.next(&lsquo;someId&rsquo;)}
${#ids.prev(&lsquo;someId&rsquo;)}</p>

<p>20 Appendix C: Markup Selector Syntax</p>

<p>Thymeleaf’s Markup Selectors are directly borrowed from Thymeleaf’s parsing library: AttoParser.</p>

<p>The syntax for this selectors has large similarities with that of selectors in XPath, CSS and jQuery, which makes them easy to use for most users. You can have a look at the complete syntax reference at the AttoParser documentation.</p>

<p>For example, the following selector will select every <div> with the class content, in every position inside the markup (note this is not as concise as it could be, read on to know why):</p>

<div th:insert="mytemplate :: //div[@class='content']">...</div>

<p>The basic syntax includes:</p>

<pre><code>/x means direct children of the current node with name x.

//x means children of the current node with name x, at any depth.

x[@z=&quot;v&quot;] means elements with name x and an attribute called z with value “v”.

x[@z1=&quot;v1&quot; and @z2=&quot;v2&quot;] means elements with name x and attributes z1 and z2 with values “v1” and “v2”, respectively.

x[i] means element with name x positioned in number i among its siblings.

x[@z=&quot;v&quot;][i] means elements with name x, attribute z with value “v” and positioned in number i among its siblings that also match this condition.
</code></pre>

<p>But more concise syntax can also be used:</p>

<pre><code>x is exactly equivalent to //x (search an element with name or reference x at any depth level, a reference being a th:ref or a th:fragment attribute).

Selectors are also allowed without element name/reference, as long as they include a specification of arguments. So [@class='oneclass'] is a valid selector that looks for any elements (tags) with a class attribute with value &quot;oneclass&quot;.
</code></pre>

<p>Advanced attribute selection features:</p>

<pre><code>Besides = (equal), other comparison operators are also valid: != (not equal), ^= (starts with) and $= (ends with). For example: x[@class^='section'] means elements with name x and a value for attribute class that starts with section.

Attributes can be specified both starting with @ (XPath-style) and without (jQuery-style). So x[z='v'] is equivalent to x[@z='v'].

Multiple-attribute modifiers can be joined both with and (XPath-style) and also by chaining multiple modifiers (jQuery-style). So x[@z1='v1' and @z2='v2'] is actually equivalent to x[@z1='v1'][@z2='v2'] (and also to x[z1='v1'][z2='v2']).
</code></pre>

<p>Direct jQuery-like selectors:</p>

<pre><code>x.oneclass is equivalent to x[class='oneclass'].

.oneclass is equivalent to [class='oneclass'].

x#oneid is equivalent to x[id='oneid'].

#oneid is equivalent to [id='oneid'].

x%oneref means &lt;x&gt; tags that have a th:ref=&quot;oneref&quot; or th:fragment=&quot;oneref&quot; attribute.

%oneref means any tags that have a th:ref=&quot;oneref&quot; or th:fragment=&quot;oneref&quot; attribute. Note this is actually equivalent to simply oneref because references can be used instead of element names.

Direct selectors and attribute selectors can be mixed: a.external[@href^='https'].
</code></pre>

<p>So the above Markup Selector expression:</p>

<div th:insert="mytemplate :: //div[@class='content']">...</div>

<p>Could be written as:</p>

<div th:insert="mytemplate :: div.content">...</div>

<p>Examining a different example, this:</p>

<div th:replace="mytemplate :: myfrag">...</div>

<p>Will look for a th:fragment=&ldquo;myfrag&rdquo; fragment signature (or th:ref references). But would also look for tags with name myfrag if they existed (which they don’t, in HTML). Note the difference with:</p>

<div th:replace="mytemplate :: .myfrag">...</div>

<p>…which will actually look for any elements with class=&ldquo;myfrag&rdquo;, without caring about th:fragment signatures (or th:ref references).
Multivalued class matching</p>

<p>Markup Selectors understand the class attribute to be multivalued, and therefore allow the application of selectors on this attribute even if the element has several class values.</p>

<p>For example, div.two will match <div class="one two three" /></p>
                        </div>

                        


                        

<div class="post-archive">
    <h2>See Also</h2>
    <ul class="listing">
        
        <li><a href="/hugo/post/java/thymeleaf/">Thymeleaf学习</a></li>
        
        <li><a href="/hugo/post/java/freemarker/">Freemarker 学习</a></li>
        
    </ul>
</div>


                        <div class="post-meta meta-tags">
                            
                            <ul class="clearfix">
                                
                                <li><a href="https://otswang.gitee.io/hugo/tags/%E6%A8%A1%E6%9D%BF%E5%BC%95%E6%93%8E">模板引擎</a></li>
                                
                                <li><a href="https://otswang.gitee.io/hugo/tags/thymeleaf">Thymeleaf</a></li>
                                
                            </ul>
                            
                        </div>
                    </article>
                    
    

    
    
                </div>
            </div>
            <div id="secondary">

    <section class="widget">
        <form id="search" action="//www.google.com/search" method="get" accept-charset="utf-8" target="_blank" _lpchecked="1">
      
      <input type="text" name="q" maxlength="20" placeholder="Search">
      <input type="hidden" name="sitesearch" value="https://otswang.gitee.io/hugo/">
      <button type="submit" class="submit icon-search"></button>
</form>
    </section>

    
    <div class="clear">
        <div class="toc-article">
            <div class="toc-title">文章目录</dixsv>
            <nav id="TableOfContents">
<ul>
<li><a href="#1-introducing-thymeleaf">1. Introducing Thymeleaf</a>
<ul>
<li><a href="#1-1-what-is-thymeleaf">1.1. What is Thymeleaf?</a></li>
<li><a href="#1-2-what-kind-of-templates-can-thymeleaf-process">1.2. What kind of templates can Thymeleaf process?</a></li>
</ul></li>
<li><a href="#2-the-good-thymes-virtual-grocery">2. The Good Thymes Virtual Grocery</a>
<ul>
<li><a href="#2-1-a-website-for-a-grocery">2.1. A website for a grocery</a></li>
<li><a href="#2-2-creating-and-configuring-the-template-engine">2.2. Creating and configuring the Template Engine</a></li>
</ul></li>
<li><a href="#3-using-texts">3. Using Texts</a>
<ul>
<li><a href="#3-1-a-multi-language-welcome">3.1. A multi-language welcome</a></li>
<li><a href="#3-2-more-on-texts-and-variables">3.2. More on texts and variables</a></li>
</ul></li>
<li><a href="#4-standard-expression-syntax">4. Standard Expression Syntax</a>
<ul>
<li><a href="#4-1-messages">4.1. Messages</a></li>
<li><a href="#4-2-variables">4.2. Variables</a></li>
<li><a href="#4-3-expressions-on-selections-asterisk-syntax">4.3. Expressions on selections (asterisk syntax)</a></li>
<li><a href="#4-4-link-urls">4.4. Link URLs</a></li>
<li><a href="#4-5-fragments">4.5. Fragments</a></li>
</ul></li>
</ul>
</nav>
        </div>
    </div>
    

</div>
        </div>
    </div>
</div>
<footer id="footer">
    <div class="container">
        &copy; 2020 <a href="https://otswang.gitee.io/hugo/">The Sky of OtsWang By OtsWang</a>.
        Powered by <a rel="nofollow noreferer noopener" href="https://gohugo.io" target="_blank">Hugo</a>.
        <a href="https://www.flysnow.org/" target="_blank">Theme</a> based on <a href="https://github.com/Dudiao137/maupassant-hugo" target="_blank">maupassant-ots</a>.
        
    </div>
</footer>


    <script type="text/javascript">
    
    (function(){
        $("pre code").parent().addClass("line-numbers")
    }())

    window.MathJax = {
        tex2jax: {
            inlineMath: [ ['$','$'] ],
            processEscapes: true
        }
    };
    </script>
    <script type="text/javascript" src="/hugo/js/prism.js" async="true"></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>

<a id="rocket" href="#top"></a>
<script type="text/javascript" src="/hugo/js/totop.js?v=0.0.0" async=""></script>







 
 <script src="https://mermaidjs.github.io/scripts/mermaid.min.js"></script>
 <script>
       mermaid.initialize({ startOnLoad: true });
 </script>
</body>
</html>
